方案一、同分不同排名
db.getCollection("userCreditHourChangeRecord").aggregate([
{
$match: {
"userNo":{
$ne: null
}
}
},
{
$group: {
"_id": "$userNo",
"userNo": {
$first: "$userNo"
},
"total": {
$sum: "$realChangeScore"
}
}
},
{
$sort: {
"total": - 1
}
},
{
$group: {
"_id": null,
"items": {
"$push": "$$ROOT"
}
}
},
{
$unwind: {
path: "$items",
includeArrayIndex: "rank"
}
},
{
$project: {
"_id": 0,
"userNo": "$items.userNo",
"total": "$items.total",
"rank": {
$add: ["$rank", 1]
}
}
}
])
结果:
方案二、同分同排名,排名连续
db.getCollection("userCreditHourChangeRecord").aggregate([
{
$match: {
"userNo": {
$ne: null
}
}
},
{
$group: {
"_id": "$userNo",
"userNo": {
$first: "$userNo"
},
"total": {
$sum: "$realChangeScore"
}
}
},
{
$group: {
"_id": "$total",
"total": {
$first: "$total"
},
"userNos": {
$push: "$userNo"
}
}
},
{
$sort: {
"total": - 1
}
},
{
$group: {
"_id": null,
"items": {
"$push": "$$ROOT"
}
}
},
{
$unwind: {
path: "$items",
includeArrayIndex: "rank"
}
},
{
$project: {
"_id": 0,
"userNos": "$items.userNos",
"total": "$items.total",
"rank": {
$add: ["$rank", 1]
}
}
},
// 按用户编号拆分
{
$unwind: {
path: "$userNos"
}
}
])
结果: