gpt4 book ai didi

MongoDB 数组和投影

转载 作者:可可西里 更新时间:2023-11-01 10:46:52 25 4
gpt4 key购买 nike

我正在学习 MongoDB,但在执行简单查询时遇到了问题。我有以下文档结构:

{
"_id" : 1,
"Title" : "Title 1",
"Author" : "Author 1",
"Comments" : [
{
"Id" : "Comment1_Id",
"User" : "User 1",
"Content" : "Content 1"
},
{
"Id" : "Comment2_Id",
"User" : "User 2",
"Content" : "Content 2"
},
{
"Id" : "Comment3_Id",
"User" : "User 3",
"Content" : "Content 3"
},
{
"Id" : "Comment4_Id",
"User" : "User 4",
"Content" : "Content 4"
},
{
"Id" : "Comment5_Id",
"User" : "User 5",
"Content" : "Content 5"
}
] }

我正在练习和做一些基本的事情。我必须找到特定给定用户发布的所有内容。我尝试了以下查询:

db.articles.find({
"Comments.User" : "User 5" },
{
"Comments.User" : 1, "Comments.Content" : 1
});

我希望

{
"_id" : 1,
"Comments" : [
{
"User" : "User 5",
"Content" : "Content 5"
}
] }

但是我明白了

{
"_id" : 1,
"Comments" : [
{
"User" : "User 1",
"Content" : "Content 1"
},
{
"User" : "User 2",
"Content" : "Content 2"
},
{
"User" : "User 3",
"Content" : "Content 3"
},
{
"User" : "User 4",
"Content" : "Content 4"
},
{
"User" : "User 5",
"Content" : "Content 5"
}
] }

我错过了什么吗?感谢您的帮助

最佳答案

Mongo 的find 返回匹配查询的整个文档,它不会只返回匹配的数组元素。

要仅返回匹配的元素,您需要进行聚合并使用展开运算符:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

关于MongoDB 数组和投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49662539/

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