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?