我有一个这样的文档结构:
{
"name":"test",
"family":"test",
score:[
{
"point":3,
"des":"blah"
},
{
"point":4,
"des":"blahblah"
},
{
"point":5,
"des":"blahblahblah!!"
},
{
"point":2,
"des":"blah!!!!"
},......
]
}
现在我想用分页获得分数部分。如何用分页对分数项进行排序和投影?
答案 0 :(得分:0)
使用您的样本数据
{
"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 }
}
])
将返回该输出
{
"score" : [
{
"point" : 3,
"des" : "blah"
},
{
"point" : 4,
"des" : "blahblah"
}
]
}
要修改页码或尺寸,只需根据需要调整$skip
和$limit
阶段的值。