Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose aggregate Lookup - How to filter by specific id

I am trying to make a aggregate pipeline - $lookup to receive from another collection only items that are not equal to specific _id

for example :

ClinicsCollection :

{_id:1,name:'some name1'}
{_id:2,name:'some name2'}
{_id:3,name:'some name3'}

BusinessCollection :

{_id:1,name:"some business name",clinics:[1,2,3]}

My aggregate pipeline query :

db.business.aggregate([
    {$match: {_id: mongoose.Types.ObjectId(businessId)}},
    {$lookup: 
    {from: "ClinicsCollection", localField: "clinics", foreignField: "_id", as: "clinics"}},

]

I want to filter all clinics that are not equal to specific id number let say _id : 1

expected result :

 clinics :[
    {_id:2,name:'some name2'}
    {_id:3,name:'some name3'}
 ]

How can i achieve that ?

Thanks

like image 572
Eran Abir Avatar asked Jan 16 '19 11:01

Eran Abir


2 Answers

You can use below aggregation with mongodb 3.6 and above

You need to just use $match with the child collection as you do with the parent collection in the first stage.

db.BusinessCollection.aggregate([
  { "$match": { "clinics": { "$type": "array" }}},
  { "$lookup": {
    "from": "ClinicsCollection",
    "let": { "clinics": "$clinics" },
    "pipeline": [
      { "$match": {
        "$expr": {
          "$and": [
            { "$in": ["$_id", "$$clinics"] },
            { "$not": { "$eq": ["$_id", 1] }}
          ]
        }
      }}
    ],
    "as": "clinics"
  }}
])
like image 115
Ashh Avatar answered Nov 16 '22 21:11

Ashh


You can try below aggregation for mongodb version below 3.6

db.business.aggregate([
    {$match : {_id : 1}},
    {$lookup : {from : "clinics", localField : "clinics", foreignField : "_id", as : "clinics"}},
    {$addFields : {clinics : {$filter : {input : "$clinics", as : "c", cond : {$ne : ["$$c._id", 1]}}}}}
]).pretty()

result

{ "_id" : 1, "name" : "some business name", "clinics" : [ { "_id" : 2, "name" : "some name2" }, { "_id" : 3, "name" : "some name3" } ] }
like image 20
Saravana Avatar answered Nov 16 '22 19:11

Saravana