How to use $lookup as INNER JOIN in MongoDB Aggregation?

前端 未结 1 456
无人及你
无人及你 2020-12-19 16:52

I have used $lookup in my aggregate query. But as I am seeing it works as LEFT OUTER JOIN.

I want to fetch exact matches doc

相关标签:
1条回答
  • 2020-12-19 17:17

    Just add the $match pipeline stage which skips documents with empty inventory_docs field. There no other way to achieve that.

    Query:

    db.getCollection('inventory').aggregate([
        {
            $lookup: {
                from: "orders",
                localField: "sku",
                foreignField: "item",
                as: "inventory_docs"
            }
        },
        {
            $match: {
                "inventory_docs": {$ne: []}
            }
        }
    ])
    

    Result:

    {
        "_id" : 1.0,
        "sku" : "abc",
        "description" : "product 1",
        "instock" : 120.0,
        "inventory_docs" : [ 
            {
                "_id" : 1.0,
                "item" : "abc",
                "price" : 12.0,
                "quantity" : 2.0
            }
        ]
    }
    
    {
        "_id" : 4.0,
        "sku" : "jkl",
        "description" : "product 4",
        "instock" : 70.0,
        "inventory_docs" : [ 
            {
                "_id" : 2.0,
                "item" : "jkl",
                "price" : 20.0,
                "quantity" : 1.0
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题