自定义MongoDB查询以返回特定的子文档

时间:2019-06-30 17:31:21

标签: javascript node.js mongodb mongodb-query aggregation-framework

确实没有与高级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。这将返回集合中的所有文档,但仍然需要遍历所有文档,由于集合会增长得很快,因此我不确定该有多快。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.collection.aggregate([
  { "$match": { "comments.owner": "aaa" }},
  { "$unwind": "$comments" },
  { "$match": { "comments.owner": "aaa" }},
  { "$replaceRoot": { "newRoot": "$comments" }}
])

Output

[
  {
    "feedback": { "thumb": "up", "userText": "nice" },
    "owner": "aaa"
  },
  {
    "feedback": { "thumb": "up", "userText": "nice" },
    "owner": "aaa"
  }
]