【问题标题】:Custom MongoDB query to return specific sub-documents自定义 MongoDB 查询以返回特定的子文档
【发布时间】:2019-06-30 17:31:21
【问题描述】:

并没有真正用于高级 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 的“cmets”字段上使用$elemMatch。这会将集合中的所有文档返回给我,但仍需要遍历所有文档,因为集合会增长得非常快,所以我不确定速度会有多快..

谢谢!

【问题讨论】:

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


    【解决方案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"
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多