Search code examples
mongodbaggregation-frameworkmongodb-aggregation

how to combine projection and pagination in mongodb?


I have a document structure such as this:

{
    "name":"test", 
    "family":"test", 
    score:[
    {
        "point":3,
        "des":"blah" 
    },
    {
        "point":4,
        "des":"blahblah" 
    },
    {
        "point":5,
        "des":"blahblahblah!!" 
    },
    {
        "point":2,
        "des":"blah!!!!" 
    },......
   ]
}

now I want get the score section with pagination. how can i sort and project item of score with pagination?


Solution

  • With your sample data like this

    {
        "name":"test", 
        "family":"test", 
        score:[
        {
            "point":3,
            "des":"blah" 
        },
        {
            "point":4,
            "des":"blahblah" 
        },
        {
            "point":5,
            "des":"blahblahblah!!" 
        },
        {
            "point":2,
            "des":"blah!!!!" 
        }
       ]
    }
    

    the following pipeline

    db.getCollection('yourCollection').aggregate([
        // .. you may want to include a $match stage here
        {
            $unwind: "$score"
        },
        {
            $sort: { "score.point": 1 }
        },
        {
            $skip: 1
        },
        {
            $limit: 2
        },
        {
            $group: {
                _id: "_id", 
                score: { $push: "$score" }
            }
        },
        {
            $project: { _id: 0, score: 1 }
        }
    ])
    

    would return that output

    {
        "score" : [ 
            {
                "point" : 3,
                "des" : "blah"
            }, 
            {
                "point" : 4,
                "des" : "blahblah"
            }
        ]
    }
    

    In order to modify the page number or size, simply adjust the value of the $skip and $limit stages to your needs.

    GIF showing working pipeline