猫鼬聚合查找-如何按特定ID进行过滤 [英] Mongoose aggregate Lookup - How to filter by specific id

查看:71
本文介绍了猫鼬聚合查找-如何按特定ID进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

ClinicsCollection:

ClinicsCollection :

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

BusinessCollection:

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

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

预期结果:

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

我该如何实现?

谢谢

推荐答案

您可以在下面使用 aggregation 和mongodb 3.6 及更高版本

You can use below aggregation with mongodb 3.6 and above

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

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

这篇关于猫鼬聚合查找-如何按特定ID进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆