How to use MongoDB aggregation for pagination?

前端 未结 1 1061
遥遥无期
遥遥无期 2021-02-01 20:31

I want to perform an aggregation query that does basic pagination:

  1. Find all orders that belongs to a certain company_id
  2. Sort the orders by
相关标签:
1条回答
  • 2021-02-01 21:11

    To calculate totals and return a subset, you need to apply grouping and skip/limit to the same dataset. For that you can utilise facets

    For example to show 3rd page, 10 documents per page:

    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
        } }
    ] )
    

    It will return a single document with 2 fields:

    {
        "metadata" : [ 
            {
                "total" : 300,
                "page" : 3
            }
        ],
        "data" : [ 
            {
                ... original document ...
            }, 
            {
                ... another document ...
            }, 
            {
                ... etc up to 10 docs ...
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题