![](/img/trans.png)
[英]Best way to handle non-existent sub-documents in MongoDB query results
[英]Custom MongoDB query to return specific sub-documents
并没有真正与高级 mongo 功能一起使用,所以我正在寻找从我的集合中返回特定字段的正确方法。 鉴于以下结构:
[
{
_id: 1,
comments: [
{
owner: "aaa",
feedback: { userText: 'nice', thumb: 'up'}
},
{
owner: "aab",
feedback: { userText: 'not nice', thumb: 'down'}
}
]
},
{
_id: 2,
comments: [
{
owner: "aac",
feedback: { userText: 'nice', thumb: 'up'}
}
]
},
{
_id: 3,
comments: [
{
owner: "aad",
feedback: { userText: 'not nice', thumb: 'down'}
},
{
owner: "aaa",
feedback: { userText: 'nice', thumb: 'up'}
}
]
}
]
我正在尝试获取属于所有者且 ID 为“aaa”的所有反馈。 输出应如下所示:
[
{
owner: "aaa",
feedback: { userText: 'nice', thumb: 'up'}
},
{
owner: "aaa",
feedback: { userText: 'nice', thumb: 'up'}
}
]
到目前为止,我所做的是在具有特定所有者 ID 的“评论”字段上使用$elemMatch
。 这将返回集合中的所有文档,但仍然需要遍历所有文档,我不确定会多快,因为集合增长得非常快..
谢谢!
您可以使用以下聚合
db.collection.aggregate([
{ "$match": { "comments.owner": "aaa" }},
{ "$unwind": "$comments" },
{ "$match": { "comments.owner": "aaa" }},
{ "$replaceRoot": { "newRoot": "$comments" }}
])
[
{
"feedback": { "thumb": "up", "userText": "nice" },
"owner": "aaa"
},
{
"feedback": { "thumb": "up", "userText": "nice" },
"owner": "aaa"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.