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
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"
}}
])
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" } ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With