我的数据库看起来像:
{
{user:bob,votes:63}
{user:jack,votes:27}
{user:john,votes:10}
}
我可以获得总票数,但我无法弄清楚如何让每个人的投票占总数的百分比。例如; jack 将拥有 27% 的选票。
[
{
'$group': {
'_id': '',
'totalofvotes': {'$sum': '$votes'},
'%votesperperson': {'$multiply':[{'$divide':["votes",{'$sum': '$votes'}]},100]}
},
}
]
最佳答案
你不能在单个小组赛阶段做到这一点,因为小组因为有总和而被终止。相反,请使用以下查询:
db['test'].aggregate(
[
// Stage 1
{
$group: {
_id:null,
sum:{$sum:"$votes"},
users:{$push:{user:"$user", votes:"$votes"}}
}
},
// Stage 2
{
$unwind: {
path : "$users",
}
},
// Stage 3
{
$project: {user:"$users.user",
votes:"$users.votes",
sum:"$sum",
"percent": {$multiply:[{$divide:["$users.votes","$sum"]},100]}
}
},
]
);
它会输出
{
"_id" : null,
"user" : "bob",
"votes" : NumberInt(63),
"sum" : NumberInt(100),
"percent" : 63.0
}
{
"_id" : null,
"user" : "jack",
"votes" : NumberInt(27),
"sum" : NumberInt(100),
"percent" : 27.0
}
{
"_id" : null,
"user" : "john",
"votes" : NumberInt(10),
"sum" : NumberInt(100),
"percent" : 10.0
}
关于mongodb - 计算mongodb中的百分比,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52514384/