How to $lookup with MongoDB C# driver?

泪湿孤枕 提交于 2019-12-05 01:39:09

问题


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


回答1:


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




回答2:


You can also achieve that using the collection.Aggregate().Lookup() method or by adding the lookup to the aggregate stages.

collection.Aggregate()
    .Lookup("foreignCollectionName", "localFieldName", "foreignFieldName", "result");



回答3:


Problem is Lookup requires Projection

Collection.Aggregate().Lookup("foreignCollectionName", "localFieldName", "foreignFieldName","result").Project(Builders<BsonDocument>.Projection.Exclude("_id"))
.ToList()

Then You need it to convert to JSON

String ConvertToJson= res[0].AsBsonDocument.ToJson();
String resultsConvertToJson = ConvertToJson.ToJson();

Then use BSONSerialize and Put it in C# Strongly typed Collection

List<TModel> results= BsonSerializer.Deserialize<List<TMModel>>(resultsConvertToJson);



回答4:


This worked for me:

var collection2 = database.GetCollection<BsonDocument>("dbACESSO");

var match1 = new BsonDocument("$match", new BsonDocument("PartnerId", cliente));
var match2 = new BsonDocument("$match", new BsonDocument("CD_CLIENTE", codCond));

var lookup1 = new BsonDocument { { "$lookup", new BsonDocument { { "from", "GRUPO_UNIDADE" }, { "localField", "CD_GRUPO_UNIDADE" }, { "foreignField", "CD_GRUPO_UNIDADE" }, { "as", "GRUPO" } } } };

var pipeline = new[] { match1, match2, lookup1 };
var result = collection2.Aggregate<BsonDocument>(pipeline).ToList();


来源:https://stackoverflow.com/questions/35638372/how-to-lookup-with-mongodb-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!