我有一個項目的集合可以upvoted或downvoted。如何在MongoDB彙總框架中處理零除
{"_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}}
]);
顯然,這是不行的,因爲分工。我需要實現適當的調節:
如果upvotes = 0和downvotes == 0則質量= upvotes 如果upvotes和downvotes均爲0,那麼質量是0
我試圖調整downvotes 1使用!三元成語。但無濟於事。
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聚合框架中集成這種調節?
這是它,我只是改變了 「N/A」 到「$ upvotes 」。無論如何,$ cond現在是我的朋友。 – gwaramadze