我的数据库如下:
{
{user:bob,votes:63}
{user:jack,votes:27}
{user:john,votes:10}
}
我可以得到投票总数,但是我不知道如何获得每个人的投票数占总数的百分比。例如;杰克将拥有27%的选票。
[
{
'$group': {
'_id': '',
'totalofvotes': {'$sum': '$votes'},
'%votesperperson': {'$multiply':[{'$divide':["votes",{'$sum': '$votes'}]},100]}
},
}
]
答案 0 :(得分:3)
您不能在单个组阶段中执行此操作,因为要终止组的原因是具有和值。而是使用以下查询:
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
}