I have a collection of items that can be upvoted or downvoted.
{\"_id\" : 1, \"name\": \"foo\", \"upvotes\" : 30, \"downvotes\" : 10}
{\"_id\" : 2, \"name\": \"b
You might want to use the $cond operator to handle this:
db.items.aggregate([
{"$project":
{
"name": "$name",
"upvotes": "$upvotes",
"downvotes": "$downvotes",
"quality": { $cond: [ { $eq: [ "$downvotes", 0 ] }, "N/A", {"$divide":["$upvotes", "$downvotes"]} ] }
}
},
{"$sort": {"quality":-1}}
]);
You want the $cond operator. http://docs.mongodb.org/manual/reference/operator/aggregation/cond/
Something like:
{"$project":
{
"name": "$name",
"upvotes": "$upvotes",
"downvotes": { $cond: [ { $eq: ["$downvotes", 0] }, 1, "$downvotes"] }
}
},