Search code examples
c#mongodbmongodb-.net-driver

Loading linked documents MongoDB Driver


I have a document which is being loaded by the MongoDB driver.

The problem is this document has another linked document by the ObjectId.

Since for my application I need the first document fully loaded, I'm loading the linked document through an IEnumerable as follows:

IMongoDatabase Database { get; set; }

public class Document1 {
  [BsonId]
  public ObjectId Id;
  public ObjectId Document2Id;

  [BsonIgnore]
  public Document2 Document2;
}

public class Document2 {
  [BsonId]
  public ObjectId Id;
  public string Foo;
  public string Bar;
}

public IEnumerable<Document1> List() {
    var 1documents = Database.GetCollection<Document1>("1documents");
    var 2documents = Database.GetCollection<Document2>("2documents");

    foreach(var document in 1documents.AsEnumerable()) {
      document.Document2 = 2documents
                              .AsEnumerable()
                              .FirstOrDefault(d => d.ID == document.Document2Id);
      yield return document;
    }
}

My problem is that the load of the Document2 is taking too long. I have a little over 500 records, which I consider a small database. And each load is taking 500ms.

Is there any other way to load linked documents through MongoDB C# Driver?


Solution

  • There is no beautiful way to join two collections.
    In your case using Lookup will help improve speed of joining collections.

    public IEnumerable<Document1> List()
    {
        var document1Collection = Database.GetCollection<Document1>("Document1");
        var document2Collection = Database.GetCollection<Document2>("Document2");
    
        var document2Lookup = document2Collection.AsQueryable().ToLookup(x => x.Id);
        foreach (var document1 in document1Collection.AsQueryable())
        {
            document1.Document2 = document2Lookup[document1.Document2Id].FirstOrDefault();
            yield return document1;
        }
    }