How to handle division by zero in MongoDB aggregation structure

I have a set of elements that can be moved or reduced.

{"_id" : 1, "name": "foo", "upvotes" : 30, "downvotes" : 10} {"_id" : 2, "name": "bar", "upvotes" : 20, "downvotes" : 0} {"_id" : 3, "name": "baz", "upvotes" : 0, "downvotes" : 0} 

I would like to use aggregation to calculate quality

 db.items.aggregate([ {"$project": { "name": "$name", "upvotes": "$upvotes" "downvotes": "$downvotes", "quality": {"$divide":["$upvotes", "$downvotes"]} } }, {"$sort": {"quality":-1}} ]); 

Obviously this does not work, because division by zero. I need to implement the corresponding condition:

if upvotes! = 0 and downvotes == 0, then quality = upvotes if upvotes and downvotes are 0, then quality is 0

I tried tweaking downvotes at 1 using a triple idiom. But to no avail.

 db.items.aggregate([ {"$project": { "name": "$name", "upvotes": "$upvotes", "downvotes": "$downvotes" ? "$downvotes": 1 } }, {"$project": { "name": "$name", "upvotes": "$upvotes" "downvotes": "$downvotes", "quality": {"$divide":["$upvotes", "$downvotes"]} } }, {"$sort": {"quality":-1}} ]); 

How can I integrate this type of conditioning into the mongodb aggregation framework?

+6
source share
2 answers

For this you can use the $ cond operator:

 db.items.aggregate([ {"$project": { "name": "$name", "upvotes": "$upvotes", "downvotes": "$downvotes", "quality": { $cond: [ { $eq: [ "$downvotes", 0 ] }, "N/A", {"$divide":["$upvotes", "$downvotes"]} ] } } }, {"$sort": {"quality":-1}} ]); 
+21
source

You need the $ cond operator. http://docs.mongodb.org/manual/reference/operator/aggregation/cond/

Sort of:

 {"$project": { "name": "$name", "upvotes": "$upvotes", "downvotes": { $cond: [ { $eq: ["$downvotes", 0] }, 1, "$downvotes"] } } }, 
+7
source

All Articles