How to handle division by zero in MongoDB aggregation framework

前端 未结 2 1888
时光说笑
时光说笑 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: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"] } 
      }
    },
    

提交回复
热议问题