MongoDB查询,项目嵌套文档?

时间:2016-11-26 16:06:45

标签: mongodb mongodb-query

我想知道这是否可行,或者我是否需要使用聚合管道?

我已阅读this等帖子,并且直觉感觉可能。

文档示例:

{
    "_id": ObjectID("5143ddf3bcf1bfab37d9c6f"),
    "permalink": "btxcacmbqkxbpgtpeero",
    "author": "machine",
    "title": "Declaration of Independence",
    "tags": [
            "study",
            "law"
    ],
    "comments": [
                  {
                    "body": "comment 1",
                    "email": "email_1@test.com",
                    "author": "machine_1"
                   },
                  {
                    "body": "comment 2",
                    "email": "email_2@test.com",
                    "author": "machine_2"
                   },
                  {
                    "body": "comment 3",
                    "email": "email_3@test.com",
                    "author": "machine_3"
                   },
    ]
    "date": ISODate("2013-03-16T02:50:27.878Z")
}

我正在尝试访问"评论"中的特定评论。在投影字段中使用dot notation的索引位置,其中包含以下内容:

db.collection.find({permalink: "btxcacmbqkxbpgtpeero"}, {'comments.0.1.': 1})

其中comments.0是字段中的第一项:数组,.1是数组中的第二个注释。

我得到的结果:

{ "_id" : ObjectID("5143ddf3bcf1bfab37d9c6f"), "comments" : [ {  }, {  }, {  } ] }

如果我带走.1,只留下comments.0,我会得到相同的结果:

{ "_id" : ObjectID("5143ddf3bcf1bfab37d9c6f"), "comments" : [ {  }, {  }, {  } ] }

如果我带走.0,只留下comments,我的评论仍然在他们的数组中:

[
   {
    "body": "comment 1",
    "email": "email_1@test.com",
    "author": "machine_1"
   },
   {
     "body": "comment 2",
     "email": "email_2@test.com",
     "author": "machine_2"
   },
   {
     "body": "comment 3",
     "email": "email_3@test.com",
     "author": "machine_3"
   }
]

可以这样做吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:2)

没有汇总:

db.collection.find({
   permalink:"btxcacmbqkxbpgtpeero"
},
{
   comments:{
      $slice:[
         0,
         1
      ]
   }
})

返回

{
   "_id":ObjectId("583af24824168f5cc566e1e9"),
   "permalink":"btxcacmbqkxbpgtpeero",
   "author":"machine",
   "title":"Declaration of Independence",
   "tags":[
      "study",
      "law"
   ],
   "comments":[
      {
         "body":"comment 1",
         "email":"email_1@test.com",
         "author":"machine_1"
      }
   ]
}

在线试用:mongoplayground.net/p/LGbVWPyVkFk

聚合:

db.collection.aggregate([
   {
      $match:{
         permalink:"btxcacmbqkxbpgtpeero"
      }
   },
   {
      $project:{
         comment:{
            $arrayElemAt:[
               "$comments",
               0
            ]
         }
      }
   }
])

返回

{
   "_id":ObjectId("583af24824168f5cc566e1e9"),
   "comment":{
      "body":"comment 1",
      "email":"email_1@test.com",
      "author":"machine_1"
   }
}