猫鼬聚合查找-如何按特定ID进行过滤

时间:2019-01-16 11:07:24

标签: mongodb mongoose mongodb-query aggregation-framework

我正在尝试建立一个汇总管道-$lookup以从另一个管道接收 仅收集不等于特定_id

的项目

例如:

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

我的聚合管道查询:

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

]

我想过滤所有不等于特定ID号的诊所,比如说_id:1

预期结果:

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

我该如何实现?

谢谢

2 个答案:

答案 0 :(得分:1)

您可以在aggregation以下与mongodb 3.6 及更高版本

一起使用

您需要像在第一阶段中对父集合一样使用$match与子集合。

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

答案 1 :(得分:0)

您可以尝试对低于3.6的mongodb版本进行以下汇总

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()

结果

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