如何在 mongodb 中结合投影和分页?

how to combine projection and pagination in mongodb?

我有这样的文档结构:

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

现在我想获得带分页的乐谱部分。我如何使用分页对得分项进行排序和投影?

使用这样的样本数据

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

以下管道

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

会return输出

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

要修改页码或大小,只需根据需要调整 $skip$limit 阶段的值。