Mongoose aggregate Lookup - How to filter by specific id

后端 未结 2 1582
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 04:37

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 :

相关标签:
2条回答
  • 2021-01-06 05:17

    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"
      }}
    ])
    
    0 讨论(0)
  • 2021-01-06 05:29

    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" } ] }
    
    0 讨论(0)
提交回复
热议问题