温馨提示:本文翻译自stackoverflow.com,查看原文请点击:.net - Fetch Reference MongoDB Driver 2.7.0
.net mongodb join mongodb-.net-driver

.net - 获取参考MongoDB驱动程序2.7.0

发布于 2020-03-27 10:37:44

Due to memory limitations I was forced to remove my datapoints from my sensors from an array into individual documents. I decided to use MongoDBRef Objects in my code to "join" the collections back together. I can create and write those MongoDBRef objects just fine into the database, and I can retrieve them, too.
But I want to now use the function to follow the reference as it is described here. However MongoDatabase is a legacy class and obsolete at this point, and the new interface IMongoDatabase doesn't implement the function. I had a look here and that function in the answer also doesn't exist anymore. Do I have to create an extra query myself from the data in the MongoDBRef object or am I missing something here?

查看更多

查看更多

提问者
FalcoGer
被浏览
140
Skami 2019-07-03 21:46

没错,您必须自己创建一个额外的查询。

一种方法是通过创建这样的扩展方法

public static TDocument FetchDBRefAs<TDocument>(this MongoDBRef dbRef, IMongoDatabase database)
{
     var collection = database.GetCollection<TDocument>(dbRef.CollectionName);

     var query = Builders<TDocument>.Filter.Eq("_id", dbRef.Id);
     return collection.Find(query).FirstOrDefault();
}

或异步版本

 public static async Task<TDocument> FetchDBRefAsAsync<TDocument>(this MongoDBRef dbRef, IMongoDatabase database)
 {
     var collection = database.GetCollection<TDocument>(dbRef.CollectionName);

     var query = Builders<TDocument>.Filter.Eq("_id", dbRef.Id);
     return await (await collection.FindAsync(query)).FirstOrDefaultAsync();
 }

可以这样称呼

var referencedEntity = entity.ReferencedEntity.FetchDBRefAs<T>(this.database))

实体看起来像什么

public class Entity
{
       [BsonId]
       [BsonRepresentation(BsonType.ObjectId)]
       public string Id { get; set; }
       public string RandomProperty { get; set; }
       public MongoDBRef ReferencedEntity { get; set; }    
}