How to handle division by zero in MongoDB aggregation framework

前端 未结 2 1872
时光说笑
时光说笑 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}}
    ]);
    
    0 讨论(0)
  • 2021-02-18 15:48

    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"] } 
      }
    },
    
    0 讨论(0)
提交回复
热议问题