首页 > 解决方案 > Mongodb - 尝试进一步过滤到文档的子数组

问题描述

我有这样的数据

{
   "_id":1,
   "v_name":"Hair Patch in Delhi",
   "v_url":"https://www.testurlvideo.com",
   "v_comments":[
      {
         "user":"Kush Khurana",
         "comment":"Awesome Video"
      },
      {
         "user":"Nikhil",
         "comment":"Keep up the good videos"
      },
      {
         "user":"Kush Khurana",
         "comment":"Very good and Awesome Video"
      }
   ]
}

但我想要下面这样的数据

{
   "_id":1,
   "v_comments":[
      {
         "user":"Nikhil",
         "comment":"Keep up the good videos"
      }
   ]
}

我在 MongoDB 中需要什么查询?

标签: mongodbmongodb-query

解决方案


您只需要$filter选择数组中的子文档并$project只输出您想要的字段。

检查这个:

db.collection.aggregate([
  {
    "$match": {
      "_id": 1
    }
  },
  {
    "$project": {
      "v_comments": {
        "$filter": {
          "input": "$v_comments",
          "as": "arr",
          "cond": {
            "$eq": [
              "$$arr.user",
              "Nikhil"
            ]
          }
        }
      }
    }
  }
])

首先$match_id(如果您只想在一个特定文档中查找,则可选)。
然后显示由那些对象过滤的$project字段。这里的例子v_commentsuserNikhil


推荐阅读