[英]How to query MongoDB to return Document but not all subdocuments?
Let's say I have a document like this:假设我有一个这样的文件:
{
_id: ObjectId("1234567890"),
author: "ABC1",
text:"this is a Post",
details: {
time: "14/05/2015",
Edit: "none"
},
comments: [
{
comment_text: "Hello",
user: "alan",
time:"20/05/2014 20:44"
},
{
comment_text: "Hi Every One",
user: "bob",
time:"20/05/2014 20:44"
},
{
comment_text: "Good morning , Alan",
user: "Alan",
time:"20/05/2014 20:44"
},
{
comment_text: "I'm bob",
user: "bob",
time:"20/05/2014 20:44"
},
],
category: "IT"
}
I want to build a query that returns this object but with only Bob's comments in the comments array.我想构建一个返回此对象的查询,但在 comments 数组中只有 Bob 的评论。
{
author: "ABC1",
text:"this is a Post",
details: {
time: "14/05/2015",
Edit: "none"
},
comments: [
{
comment_text: "Hi Every One",
user: "bob",
time:"20/05/2014 20:44"
},
{
comment_text: "I'm bob",
user: "bob",
time:"20/05/2014 20:44"
},
],
category: "IT"
}
How can this be done?如何才能做到这一点?
$unwind
(and $match
) in an aggregation pipeline will get me the correct subdocuments, but not as an array of objects within the original document.在聚合管道中使用$unwind
(和$match
)将使我获得正确的子文档,但不会作为原始文档中的对象数组。$elemMatch
within a projection (with find()
or findOne()
) only returns the first matching comment (subdocument).在投影中使用$elemMatch
(使用find()
或findOne()
)只返回第一个匹配的注释(子文档)。You can use the $filter
operator in the $project
stage of an aggregation pipeline:您可以在聚合管道的$project
阶段使用$filter
运算符:
db.collection.aggregate([
{
$project: {
_id: 0,
author: 1,
text: 1,
details: 1,
category: 1,
comments: {
$filter: {
input: "$comments",
as: "comment",
cond: {
$eq: [
"$$comment.user",
"bob"
]
}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.