title: How to handle division by zero in MongoDB aggregation framework
body: <p>I have a collection of items that can be upvoted or downvoted.</p>
  
  <pre><code>{"_id" : 1, "name": "foo", "upvotes" : 30, "downvotes" : 10}
  {"_id" : 2, "name": "bar", "upvotes" : 20, "downvotes" : 0}
  {"_id" : 3, "name": "baz", "upvotes" : 0,  "downvotes" : 0}
  </code></pre>
  
  <p>I'd like to use aggregation to calculate the quality</p>
  
  <pre><code>db.items.aggregate([
      {"$project":
          {
              "name": "$name",
              "upvotes": "$upvotes"
              "downvotes": "$downvotes",
              "quality": {"$divide":["$upvotes", "$downvotes"]}
          }
      },
      {"$sort": {"quality":-1}}
  ]);
  </code></pre>
  
  <p>Obviously this doesn't work, because of division by zero. I need to implement appropriate conditioning:</p>
  
  <p>if upvotes != 0 and downvotes == 0 then the quality = upvotes
  if upvotes and downvotes are both 0 then the quality is 0</p>
  
  <p>I tried tweaking downvotes by 1 using ternary idiom. But to no avail.</p>
  
  <pre><code>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}}
  ]);
  </code></pre>
  
  <p>How can I integrate this kind of conditioning within mongodb aggregation framework?</p>