【问题标题】:How to limit nested object in MongoDB aggregation query如何在 MongoDB 聚合查询中限制嵌套对象
【发布时间】:2021-12-07 00:36:12
【问题描述】:

我正在开发一个带有ExpressnodeJS 服务,它使用MongoDB 作为数据库,并且我有包含嵌套对象的文档。 我想要限制和分页聚合嵌套列表。

我的文件格式如下:

{
    "_id": "61ae0f28131a77c9d5bbf242",
    "time": 137537200058,
    "description": "fake logs",
    "data": "fake data",
    "device": {
        "model": "iPhone"
    }
}

这是 mongo 查询

const db = request.client.db( DATABASE_NAME );
db.collection( COLLECTION_NAME )
    .aggregate([
        { $group : { _id : "$device.model", logs: { $push: "$$ROOT" } } } ,
        { $sort: { _id: 1 } },
    ])
    .skip( 5 )
    .limit( 2 ) // <--------------- limit only aggregation
    .toArray()
    .then( docs => {
        response.send({
            status: STATUS_SUCCESS,
            data: docs
        });
    })
;

limit() 在我的查询中,只限制根,但嵌套对象没有限制

查询结果示例

{
    "_id": "Android",
    "logs": [
        {
            "_id": "61ae0f28131a77c9d5bbf22f",
            "time": 1231146117734,
            "description": "fake logs",
            "data": "fake data",
            "device": {
                "model": "Android"
            }
        },
        ... // <-------------- no-limits
    ]
},
{
    "_id": "iPhone",
    "logs": [
        {
            "_id": "...",
            "time": 1231146117734,
            "description": "fake logs",
            "data": "fake data",
            "device": {
                "model": "iPhone"
            }
        },
        ... // <-------------- no-limits
    ]
}

【问题讨论】:

    标签: node.js mongodb express aggregation-framework


    【解决方案1】:

    您是否尝试在日志数组上使用$slice

    https://docs.mongodb.com/manual/reference/operator/projection/slice/

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2021-07-03
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-01-24
      • 2015-03-10
      • 1970-01-01
      相关资源
      最近更新 更多