How to handle division by zero in MongoDB aggregation framework

前端 未结 2 1886
时光说笑
时光说笑 2021-02-18 15:07

I have a collection of items that can be upvoted or downvoted.

{\"_id\" : 1, \"name\": \"foo\", \"upvotes\" : 30, \"downvotes\" : 10}
{\"_id\" : 2, \"name\": \"b         


        
2条回答
  •  臣服心动
    2021-02-18 15:42

    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}}
    ]);
    

提交回复
热议问题