0

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?

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.