首页 > 解决方案 > Mongoose中的多个嵌套过滤器

问题描述

我的 json 将是这样的:

 {
      "proj_id" : objectId1
      "author": {},
      "message": "This is post1",
      "comments": [
        {
          "insId" : objectId1
          "message": "Hii",
        "location": [
                     {"select":"Y",id:1},
             {"select":"N",,id:2}
            ]

    },
    {
      "insId" : objectId2
        "message": "Hii2",
        "location": [
                 {"select":"Y",id:1},
         {"select":"N",,id:2}
        ]
    },

  ]
},
{
  "proj_id" : objectId2
  "author": {},
  "message": "This is post2",
  "comments": [
    {
      "insId" : objectId1
      "message": "welcome2",
      location: [
                 {"select":"Y",id:1},
         {"select":"N",,id:2}
        ]

    },

    {
    "insId" : objectId2
        "message": "welcome4",
        "location": [
                 {"select":"Y",id:1},
         {"select":"N",,id:2}
        ]

    }
  ]
}

预期输出:

{
  "proj_id" : objectId1
  "author": {},
  "message": "This is post1",
  "comments": [
    {
      "insId" : objectId1
      "message": "Hii",
    "location": [
                 {"select":"Y",id:1},
        ]

    }
  ]
}

必须根据检查 ID 和内部检查 dat 进行过滤 我必须仅列出状态为“Y”的位置

我通过使用检查 ID 过滤来尝试以下代码

mongo.inspection.aggregate([
    {$match: {"comments.insId": ObjectId(req.body.insId),"projectID":ObjectId(req.body.proj_id) }},
    {$addFields : {"comments":{$filter:{ // We override the existing field!
    input: "$comments",
    as: "comments",
    cond: {$eq: ["$$comments.insId", ObjectId(req.body.insId)]}

    }}}}

],function(err,response){
console.log(response);
}

输出 :

{
  "proj_id" : objectId1
  "author": {},
  "message": "This is post1",
  "comments": [
    {
      "insId" : objectId1
      "message": "Hii",
    "location": [
                 {"select":"Y",id:1},
         {"select":"N",id:1}, // But it should not be list
        ]

    }
  ]
}

因此,我必须根据 comments.insId 过滤对象,并且必须从该单个对象中删除基于 status 的位置内的对象。我如何在猫鼬中得到这个结果

标签: node.jsmongodbmongoosefilteraggregation-framework

解决方案


$map$filter. _

就像是

{
  "$addFields":{
    "comments":{
      "$map":{
        "input":{
          "$filter":{
            "input":"$comments","as":"commentsf","cond":{"$eq":["$$commentsf.insId", ObjectId(req.body.insId)]}
          }
        },
        "as":"commentsm",
        "in":{
          "insId":"$$commentsm.insId",
          "message":"$$commentsm.message",
          "location":{"$filter":{"input":"$$commentsm.location","as":"location","cond":{"$eq":["$$location.select","Y"]}}}
        }
      }
    }
  }
}

推荐阅读