如何在C#中使用管道和let参数进行$lookup操作(MongoDB.Driver 2.7.2)

5
我需要在我的C#代码中在MongoDB中运行以下查询。我使用的是MongoDB.Driver 2.7.2和MongoDB 4.0。
我想使用$lookup而不是$project/$unwind,以避免命名集合的每个可能字段。
db.getCollection('Collection1').aggregate([  
    { "$match" : { "Id" : 1 } },
        { "$lookup": {
            "from": "Collection2",
            "let": { collection1Id : "$Id" },
            "pipeline": [
                { $match:
                    { $expr:
                        { $and:
                            [
                                { $eq : [ "$Collection1Id",  "$$collection2Id" ] },
                                { $in : [ "$_id" , [1, 2, 3]] }
                            ]
                            }
                        }
                    }
            ],
            "as": "item"
        }
    } 
])

我希望将Collection1和Collection2在多个连接条件下进行连接并输出结果。
1个回答

6

由于您没有指定特定的类映射和示例文档,因此下面的答案将使用 BsonDocument 类型和手册中的示例数据 $lookup: specify multiple join conditions with lookup


BsonArray subpipeline = new BsonArray();

subpipeline.Add(
    new BsonDocument("$match",new BsonDocument(
        "$expr", new BsonDocument(
        "$and", new BsonArray { 
             new BsonDocument("$eq", new BsonArray{"$stock_item", "$$order_item"} ), 
             new BsonDocument("$gte", new BsonArray{"$instock", "$$order_qty"} )
             }  
        )
    ))
);

var lookup = new BsonDocument("$lookup", 
                 new BsonDocument("from", "warehouses")
                             .Add("let", 
                                 new BsonDocument("order_item", "$item")
                                             .Add("order_qty", "$ordered"))
                             .Add("pipeline", subpipeline)
                             .Add("as", "stockdata")
);

var results = collection.Aggregate()
                        .Match(new BsonDocument("_id", 1))
                        .AppendStage<BsonDocument>(lookup).ToEnumerable();

foreach (var x in results)
{
    Console.WriteLine(x.ToJson());
} 

请注意,将为版本 2.8.x 提供更多表现力强的$lookup支持,使用PipelineDefinitionBuilder。有关更多信息,请参见CSHARP-2013

我很高兴这很快就会到来。谢谢你的回答! - SharonReytan
有没有关于如何使用PipelineDefinitionBuilder的官方示例,还是我们只有带有模糊描述和没有实际价值的签名?我已经花了第二天的时间来应对完全不直观和未完成的C# API,尝试连接一个假装拥有世界上最差查询语言的数据库。 - Endrju

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