Search code examples
c#mongodbmongodb-.net-driver

How to $lookup with MongoDB C# driver?


How do I perform a $lookup with the MongoDB C# driver? I cannot find it in their driver doc here:

https://docs.mongodb.org/getting-started/csharp/query/

But if I understand this ticket in their JIRA correctly, it should be in the 2.2 version of the driver:

https://jira.mongodb.org/browse/CSHARP-1374


Solution

  • If you use the AsQueryable() extension method on IMongoCollection<T>, you can then use the LINQ interface, as an example.

    var query = from p in collection.AsQueryable()
                join o in otherCollection on p.Name equals o.Key into joined
                select new { p.Name, AgeSum: joined.Sum(x => x.Age) };
    

    This was copied from the mongodb csharp driver documentation here http://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/crud/linq/#lookup