I have a collection of items that can be upvoted or downvoted.
{"_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'd like to use aggregation to calculate the quality
db.items.aggregate([
{"$project":
{
"name": "$name",
"upvotes": "$upvotes"
"downvotes": "$downvotes",
"quality": {"$divide":["$upvotes", "$downvotes"]}
}
},
{"$sort": {"quality":-1}}
]);
Obviously this doesn't work, because of division by zero. I need to implement appropriate conditioning:
if upvotes != 0 and downvotes == 0 then the quality = upvotes if upvotes and downvotes are both 0 then the quality is 0
I tried tweaking downvotes by 1 using ternary 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 kind of conditioning within mongodb aggregation framework?