【问题标题】:Mongoose aggregate Lookup - How to filter by specific idMongoose 聚合查找 - 如何按特定 id 过滤
【发布时间】:2019-06-10 11:03:56
【问题描述】:

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

例如:

诊所集合:

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

业务集合:

{_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'}
 ]

我怎样才能做到这一点?

谢谢

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案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"
      }}
    ])
    

    【讨论】:

    • err : MongoError : $in 需要一个数组作为第二个参数,发现:缺少
    • 哦,在我的数据库中,它是业务中的clinicsIds .. 抱歉,我如何才能从查找中仅获取特定字段?谢谢
    • 这里为什么需要一个让?
    【解决方案2】:

    您可以尝试以下聚合 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" } ] }
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2023-03-23
      • 2020-06-06
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多