MongoDB查询,如何对嵌套文档进行投影?

3
我在想这是否可能,还是我需要使用聚合管道?
我已阅读过像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")
}

我正在尝试使用投影字段中的点符号通过索引位置访问“评论”中的特定评论,具体方法如下:
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
可能是MongoDB:使用$定位符号进行查询的重复问题。 - Neo-coder
@Yogesh 不完全正确;该帖子侧重于使用$ operator。我试图明确指定元素的索引位置。 “定位符$运算符标识要更新的数组中的元素,而不明确指定元素在数组中的位置。” 另外,我正在查询并在投影字段中使用它,而文档似乎表明$运算符用于更新。 - Jake Stokes
为此,您可以尝试使用**$arrayElement$slice**。 - Neo-coder
1个回答

3

没有聚合:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接