mongo aggregate if null or zero return 1


When we have situation $divide some number field value can be a zero or null, then aggregate will fail with error, so we may need to default value in some case, so hope this article and example will help

PlanExecutor error during aggregation :: caused by :: can’t $divide by zero

Here’s an example of using the MongoDB aggregation framework to return 1 if a value is either null or zero:

<code class="">db.collection.aggregate([
    $project: {
      value: {
        $cond: [
          { $or: [ { $eq: [ "$value", null ] }, { $eq: [ "$value", 0 ] } ] },

In this pipeline, the $project stage is used to create a new field value that uses the $cond operator to determine the value of the field. The $cond operator takes three arguments: a condition, the value to return if the condition is true, and the value to return if the condition is false. In this case, the condition checks whether value is either null or 0 using the $or operator and the $eq operator. If the condition is true, the value will be set to 1, otherwise it will be set to the original value of the value field.

Posted in MongoDB and tagged , by .

About Gowri

I am professional web developer with 8+ years experience. PHP, jQuery, WordPress, Angular and Ionic are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.