My db looks like:
{
{user:bob,votes:63}
{user:jack,votes:27}
{user:john,votes:10}
}
I can get the total of the votes, but I can't figure out how to get each persons vote as a percentage of the total. For example; jack would have 27% of the vote.
[
{
'$group': {
'_id': '',
'totalofvotes': {'$sum': '$votes'},
'%votesperperson': {'$multiply':[{'$divide':["votes",{'$sum': '$votes'}]},100]}
},
}
]
you can't do this in a single group stage, as group as to be terminated for having sum value. Instead, use the following query :
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]}
}
},
]
);
It will output
{
"_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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With