简体   繁体   中英

How to limit nested object in MongoDB aggregation query

I'm developing a nodeJS service with Express that use MongoDB as Database, and I have documents with nested objects. I want limit and paginate aggregation nested list.

My documents is in this format:

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

this is mongo query

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() in my query, limit only the root but nested objects have no limit

Example of query result

{
    "_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
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM