How to $lookup with pipeline & let parameters in C# (MongoDB.Driver 2.7.2)

℡╲_俬逩灬. 提交于 2019-12-11 05:13:47

问题


I need to run the following query in MongoDB in my C# code. I use MongoDB.Driver 2.7.2 and MongoDB 4.0.

I would like to use $lookup rather than $project / $unwind in order to prevent naming each one of the collection's possible fields.

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"
        }
    } 
])

I expect the output of Collection1 joined with Collection2 under multiple join conditions.


回答1:


As you didn't specify a particular class mapping and example documents, below answer will use BsonDocument type and example data from the manual $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());
} 

Please note that support for more expressive $lookup using PipelineDefinitionBuilder is coming for version 2.8.x. For more information see CSHARP-2013



来源:https://stackoverflow.com/questions/54305932/how-to-lookup-with-pipeline-let-parameters-in-c-sharp-mongodb-driver-2-7-2

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