如何使用MongoDB C#驱动程序进行$lookup操作?

10

2
我猜你指的是缺少“helper”方法,这是可以预料的,因为大多数实现此类功能的驱动程序都落后于新服务器版本的功能。聚合管道与普通查询一样,只是 BSON 结构。任何您可以构造为 BSON 文档的内容都可以作为输入提供给 .find().aggregate(),只要它是有效的。因此,直接构建 BSON 文档作为管道即可。当然,前提是您有 MongoDB 3.2 服务器来支持 $lookup。这是决定性因素。 - Blakes Seven
请注意,比这里显示的使用C#进行聚合$lookup更完整的示例。展示了驱动程序的所有可查询形式以及流畅构建器。 - Neil Lunn
5个回答

21

otherCollection 是什么类型? - thepirat000
4
你需要使用 MongoDB.Driver.Linq 命名空间来使它起作用。 - tigrou
@tigrou 对我来说,System.Linq 已经足够了。 - Beingnin

18
您也可以使用collection.Aggregate().Lookup()方法或将查找添加到聚合阶段来实现此目的。
collection.Aggregate()
    .Lookup("foreignCollectionName", "localFieldName", "foreignFieldName", "result");

聚合管道查询怎么样? - Homam
1
@Homam 这里有一个非常详细的答案:https://dev59.com/sVUL5IYBdhLWcg3wUWmt - M. Mennan Kara

4
问题是查找需要投影。
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);

你能解释一下我们是否可以直接从你的第一部分获取结果吗?而不需要转换为JSON格式。 - Hridoy_089

4
这是我的解决方案:

这对我起作用:

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

2
除了已经提到的内容,您还可以使用类型安全的重载版本来查找方法。
Lookup是一个扩展方法,用于您的本地集合,接受4个参数,第一个是外部集合,第二个是指向本地字段的表达式,第三个是指向外部字段的表达式,第四个是将连接结果映射到输出类型中的字段的表达式。
_fromTypeCollection.Aggregate<fromType>()
.Lookup<fromType,targetType,outputType>(targetTypeCollection,
fromType => fromType.localFeild, 
targetType => targetType.foreignField, 
outputType => outputType.result);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接