gpt4 book ai didi

MongoDB 查询,项目嵌套文档?

转载 作者:行者123 更新时间:2023-12-05 04:12:19 30 4
gpt4 key购买 nike

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

我读过类似 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"
}
]

这能做到吗?如果是,怎么办?

最佳答案

没有聚合:

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

关于MongoDB 查询,项目嵌套文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820263/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com