Sourabh Bhutani
Sourabh Bhutani

Reputation: 663

In MongoDB how to use $lookup to get not matched records only?

In Mongodb, I want to get data of those products who don't have any order.

Collections : master_product_details, master_order_details

I'm using normal $lookup query which is giving all records of matched or unmatched with order.

db.master_product_details.aggregate([
        { 
        $match: { seller_user_id : 'seller_id' } 
        },
        {
        $lookup : {from: "master_order_details",localField: "seller_sku_id", foreignField: "sku_id", as : "Orders"} 
        },
        {$unwind : '$Orders'},
        {$project : { seller_sku_id : 1, product_title : 1, _id : 0}

            }
        ])

Any other way to get result ?

Upvotes: 11

Views: 4968

Answers (1)

Ashh
Ashh

Reputation: 46441

Use one more $match condition at the end of the pipeline

db.master_product_details.aggregate([
  { "$match": { "seller_user_id": "seller_id" }},
  { "$lookup": {
    "from": "master_order_details",
    "localField": "seller_sku_id",
    "foreignField": "sku_id",
    "as": "Orders"
  }},
  { "$match": { "Orders": [] }}
])

Upvotes: 18

Related Questions