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 ] } ] }, 1, "$value" ] } } } ])</code>
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.