Warm tip: This article is reproduced from stackoverflow.com, please click
.net mongodb join mongodb-.net-driver

Fetch Reference MongoDB Driver 2.7.0

发布于 2020-03-27 10:18:30

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?

Questioner
FalcoGer
Viewed
81
Skami 2019-07-03 21:46

You are correct, you'll have to create an extra query yourself.

A way to do this is by creating an extension method like this

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();
}

or the Async edition

 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();
 }

which can be called like this

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

Where entity looks like

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