【问题标题】:MongoDB query to handle/fetch inner array (Need to apply pagination in inner array)MongoDB查询处理/获取内部数组(需要在内部数组中应用分页)
【发布时间】:2020-11-13 02:14:38
【问题描述】:

我有一个包含如下文档的集合,

Document1:

{
    name: "tester1",
    reports: [{
            name: "report1",
            type: "overflow"
        },
        {
            name: "report2",
            type: "invalid form"
        }
    ]
}

Document2:

{
    name: "tester2",
    reports: [{
            name: "report3",
            type: "crossed"
        },
        {
            name: "report4",
            type: "unknown issue"
        }
    ]
} 

Document3:
{
    name: "tester3",
    reports: [{
            name: "report4",
            type: "try again"
        },
        {
            name: "report6",
            type: "invalid data"
        }
    ]
}

我正在尝试实现查询以获取数据,例如,

[{
        name: "report1",
        type: "overflow"
    },
    {
        name: "report2",
        type: "invalid form"
    },
    {
        name: "report3",
        type: "crossed"
    },
    {
        name: "report4",
        type: "unknown issue"
    },
    {
        name: "report4",
        type: "try again"
    },
    {
        name: "report6",
        type: "invalid data"
    }
]

我尝试使用分组和投影,但无法生成此输出。

我只需要内部数组作为最终文档,这样我就可以应用聚合查询来实现分页和搜索。

【问题讨论】:

  • 每个文档都包含上面的数组?我正在尝试理解您的文档
  • 不,我已经添加了三个带数据的文档
  • 你需要做什么样的“搜索”?

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


【解决方案1】:

您可以使用$unwind$replaceRootreports 提升到根级别,然后您可以使用$skip$limit

db.collection.aggregate([
    { $unwind: "$reports" },
    { $replaceRoot: { newRoot: "$reports" } },
    { $limit: 5 }
])

Mongo Playground

【讨论】:

    猜你喜欢
    • 2022-08-19
    • 2019-07-30
    • 1970-01-01
    • 2011-10-07
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多