我正在学习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"
}
] }
我错过了什么吗?谢谢你的帮助
答案 0 :(得分:0)
Mongo的find
返回与查询匹配的整个文档,它不会仅返回匹配的数组元素。
要返回匹配的元素,您需要进行聚合并使用展开运算符:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/