如何在MongoDB聚合框架中处理零除 [英] How to handle division by zero in MongoDB aggregation framework
本文介绍了如何在MongoDB聚合框架中处理零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收集了可以上调或下调的项目.
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}
我想用聚合来计算质量
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:
如果赞成!= 0且反对== 0,则质量=赞成 如果upvotes和downvotes均为0,则质量为0
if upvotes != 0 and downvotes == 0 then the quality = upvotes if upvotes and downvotes are both 0 then the quality is 0
我尝试使用三元成语将数字减1.但是无济于事.
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}}
]);
如何在mongodb聚合框架中集成这种条件?
How can I integrate this kind of conditioning within mongodb aggregation framework?
推荐答案
您可能想使用 $ cond 运算符来处理此问题:
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}}
]);
这篇关于如何在MongoDB聚合框架中处理零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文