pythonmongodbaggregatepymongoifnull

MongoDB conditional (sum if exists, else zero)


I am trying to sum across a field within an aggregate pipeline where the field may not exist. Otherwise, the return should be zero. This is my code so far:

admits = [
    {'$match': {'meta.State': item['state'],'meta.County': item['county'], 'meta.first_seen': date}},
    {'$group': {'_id': {'item': '$item'}, 'admissions': {'$ifNull': [{'$sum': 1}, 0]}}},
]

This does not work, because calling $sum within an $ifNull raises a unary operator exception:

pymongo.errors.OperationFailure: The $ifNull accumulator is a unary operator

Solution

  • pymongo.errors.OperationFailure: The $ifNull accumulator is a unary operator

    The <accumulator> operator must be one of the following accumulator operators: accumulator-operator, and $ifNull operator is not one of them,

    The $sum operator must be in root if you want to sum,

    The usage of $ifNull is:

    Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.

    So $ifNull will not fulfil your requirement,

    You can try $cond operator to check if field type is missing then then 0 otherwise 1,

    {
      '$group': {
        '_id': {'item': '$item'}, 
        'admissions': {
          $sum: {
            $cond: [{ $eq: [{ $type: "$admissions" }, "missing"] }, 0, 1]
          }
        }
      }
    },