Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate percentage in mongodb

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]}                   
              },
  }
]
like image 324
Sonnerz Avatar asked Sep 26 '18 09:09

Sonnerz


1 Answers

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
}
like image 134
matthPen Avatar answered Oct 17 '22 09:10

matthPen