如何在MongoDB聚合框架中处理除零

时间:2014-04-03 14:50:16

标签: 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聚合框架中集成这种条件?

2 个答案:

答案 0 :(得分:33)

您可能希望使用$cond运算符来处理此问题:

db.items.aggregate([
    {"$project":
        {
            "name": "$name",
            "upvotes": "$upvotes",
            "downvotes": "$downvotes",
            "quality": { $cond: [ { $eq: [ "$downvotes", 0 ] }, "N/A", {"$divide":["$upvotes", "$downvotes"]} ] }
        }
    },
    {"$sort": {"quality":-1}}
]);

答案 1 :(得分:7)

你想要$ cond运算符。 http://docs.mongodb.org/manual/reference/operator/aggregation/cond/

类似的东西:

{"$project":
  {
    "name": "$name",
    "upvotes": "$upvotes",
    "downvotes": { $cond: [ { $eq: ["$downvotes", 0] }, 1, "$downvotes"] } 
  }
},