Mongoose aggregate Lookup - How to filter by specific id

不问归期 提交于 2020-01-04 12:50:01

问题


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


回答1:


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"
  }}
])



回答2:


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" } ] }


来源:https://stackoverflow.com/questions/54215731/mongoose-aggregate-lookup-how-to-filter-by-specific-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!