Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 532
Sourabh Bhutani Avatar asked Jan 25 '19 09:01

Sourabh Bhutani


People also ask

What is $lookup in MongoDB?

The $lookup operator is an aggregation operator or an aggregation stage, which is used to join a document from one collection to a document of another collection of the same database based on some queries. Both the collections should belong to the same databases.

Is it possible to do a $lookup aggregation between two databases in MongoDB?

We can join documents on collections in MongoDB by using the $lookup (Aggregation) function. $lookup(Aggregation) creates an outer left join with another collection and helps to filter data from merged data.

Can we use $match in Find MongoDB?

We can also use a match operator for the aggregation pipeline. In the above syntax, we use the $match Mongodb operator as shown. Here $ match is used to specify the match operator and inside the bracket, we need to write a specified required query statement that matches the condition.


1 Answers

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": [] }}
])
like image 66
Ashh Avatar answered Oct 06 '22 17:10

Ashh