Search code examples
c#mongodbmongodb-.net-driver

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


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.


Solution

  • 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