如何解决如何查询以取得最高点的排名文件
在MongoDB中,文档以这种格式保存。 我希望以这样的方式提取数据,即userId具有最高的最高排名总积分。我是MongoDB中的新手。请帮助我如何使用查询。
此数据保存在MongoDB中。
async function fetchData (url,{ type = 'json' } = {}) {
return await (await fetch(url))[type]();
}
// Example:
(async () => {
console.log(await fetchData('http://canskit.com',{ type: 'text' }));
})();
我尝试了此查询,但没有用。
[{
_id:"33fa7277-d882-4add-9985-e92c3e48c15b",user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06141",points_total:280
},{
_id:"33fa7277-d882-4add-9985-e92c3e48c25b",user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06142",points_total:200
},{
_id:"33fa7277-d882-4add-9985-e92c3e48c35b",points_total:20
},{
_id:"33fa7277-d882-4add-9985-e92c3e48c45b",user_id:"a86302a0-2b5b-4392-95c6-6b41a4d06144",points_total:150
}]
预期产量
db.users.aggregate([
{ "$sort": {"points_total" : -1}},{ "$group": {
"_id": "$user_id","points_total":{"$sum": "$points_total"},"items": { "$push": "$$ROOT" }
}},{ "$unwind": { "path": "$items","includeArrayIndex": "items.rank" } },{ "$replaceRoot": { "newRoot": "$items" } },{ "$sort": { "points_total" : -1} }
])
解决方法
在应用$group
之前,您还需要一个$unwind
才能使所有用户集中在一个阵列中。
db.users.aggregate([
{
$group: {
_id: "$user_id",points_total: { $sum: "$points_total" }
}
},{
$sort: { points_total: -1 }
},{
$group: {
_id: null,users: { $push: { user_id: "$_id",points_total: "$points_total" } }
}
},{ "$unwind": { "path": "$users","includeArrayIndex": "users.rank" } },{
$replaceRoot: {
newRoot: "$users"
}
},{
$addFields: {
rank: { $add: [ "$rank",1 ] }
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。