如何用MongoDB C#驱动程序查找?

时间:2016-02-25 21:08:19

标签: c# mongodb mongodb-.net-driver

如何使用MongoDB C#驱动程序执行$ ​​lookup?我在这里的驱动程序文档中找不到它:

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

但如果我在JIRA中正确理解这张票,它应该是2.2版本的驱动程序:

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

5 个答案:

答案 0 :(得分:11)

您也可以使用collection.Aggregate().Lookup()方法或将查找添加到聚合阶段来实现这一目标。

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

答案 1 :(得分:4)

如果在IMongoCollection< T>上使用AsQueryable()扩展方法,则可以使用LINQ接口作为示例。

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

这是从mongodb csharp驱动程序文档http://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/crud/linq/#lookup

复制而来的

答案 2 :(得分:1)

问题是查找需要投影

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

然后您需要将其转换为JSON

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

然后使用BSONSerialize并将其放入C#强类型集合中

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

答案 3 :(得分:0)

这对我有用:

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

答案 4 :(得分:0)

除了大家已经提到的以外,您可以使用的查找方法有一个类型安全的重载。

查找是本地集合的扩展方法,接受4个参数,第一个是外部集合,第二个是对本地字段的表达式,第三个是对外部字段的表达式,第四个是以下表达式将联接结果映射到您的输出类型的字段中。

_fromTypeCollection.Aggregate<fromType>()
.Lookup<fromType,targetType,outputType>(targetTypeCollection,
fromType => fromType.localFeild, 
targetType => targetType.foreignField, 
outputType => outputType.result);