Abhi
Abhi

Reputation: 6568

$sum in MongoDB query

I have to find the total votes (funny + useful + cool) from the below collection. How can i achive this using Mongo aggregate function

{
    "_id" : ObjectId("5419a8856039fe9f52640bd1"),
    "votes" : {
        "funny" : 0,
        "useful" : 2,
        "cool" : 1
    },

    "business_id" : "vcNAWiLM4dR7D2nwwJ7nCA"
}
,
{
    "_id" : ObjectId("5419a8866039fe9f52640bd2"),
    "votes" : {
        "funny" : 0,
        "useful" : 2,
        "cool" : 0
    },

    "business_id" : "vcNAWiLM4dR7D2nwwJ7nCA"
}

I tried the following

db.review.aggregate([ { 
    $project: { 

        total_votes:  
           "$votes.funny"+ "$votes.useful"  + "$votes.cool"

    } 
} ] ,
{
   allowDiskUse : true
}) 

but am getting

uncaught exception: aggregate failed: { "errmsg" : "exception: aggregation result exceeds maximum document size (16MB)", "code" : 16389, "ok" : 0 }

Is there any alternative ways to achieve this?

Upvotes: 0

Views: 115

Answers (2)

Abhay PS
Abhay PS

Reputation: 4175

This can be done like this -

db.review.aggregate([ 
{ $project : { 'total_votes' : { $add : ["$votes.funny", "$votes.useful", "$votes.cool" ]  } }  }
])

Hope the result is exactly what you need.

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311835

You can use the $add aggregation operator to do this:

db.review.aggregate([
    {$project: {
        total_votes: {$add: ['$votes.funny', '$votes.useful', '$votes.cool']}
    }}
])

Output:

{
    "result" : [ 
        {
            "_id" : ObjectId("5419a8856039fe9f52640bd1"),
            "total_votes" : 3
        }, 
        {
            "_id" : ObjectId("5419a8866039fe9f52640bd2"),
            "total_votes" : 2
        }
    ],
    "ok" : 1
}

Upvotes: 2

Related Questions