【发布时间】:2017-04-10 18:09:09
【问题描述】:
我想知道这是否可能,还是我需要使用聚合管道?
看过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 通过索引位置访问“cmets”中的特定评论,并使用以下内容:
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,我会得到 cmets 仍在它们的数组中:
[
{
"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"
}
]
这可以吗?如果有,怎么做?
【问题讨论】:
-
@Yogesh 不完全;该帖子的重点是使用$ operator。我正在尝试使用元素的索引显式指定位置。 “位置 $ 运算符标识要更新的数组中的元素没有明确指定数组中元素的位置”。我也在查询,并在投影字段,而文档似乎说 $ 运算符用于更新。
-
为此,您应该尝试 $arrayElement 或 $slice
标签: mongodb mongodb-query