MongoDB aggregation for pagination

PHOTO EMBED

Thu Feb 16 2023 05:30:40 GMT+0000 (Coordinated Universal Time)

Saved by @jaimin #aggregation #mongodb #pagination

db.Order.aggregate([
    { '$match'    : { "company_id" : ObjectId("54c0...") } },
    { '$sort'     : { 'order_number' : -1 } },
    { '$facet'    : {
        metadata: [ { $count: "total" }, { $addFields: { page: NumberInt(3) } } ],
        data: [ { $skip: 20 }, { $limit: 10 } ] // add projection here wish you re-shape the docs
    } }
] )
content_copyCOPY

apply pagination for listing

https://stackoverflow.com/questions/48305624/how-to-use-mongodb-aggregation-for-pagination