My goal is to compute the sum of conditional fields. Let’s say I have a collection of documents containing always a and b fields, and sometimes c. I want to aggregate the values of c when it exists, or b when c does not exist.
Here is a snippet:
db.create_collection("test")
coll = db["test"]
coll.insert_many([{"a":5, "b":8}, {"a":3, "b":3, "c":4}, {"a":5, "b":1}, {"a":2, "b":7, "c":9}])
result = coll.aggregate([
{"$addFields": {"d": {"$cond": [{"$eq": ["$c", None]}, "$b", "$c"]}}},
{"$group": {
"_id": None,
"total": {"$sum": "$d"},
"count": {"$sum": 1}
}}
])
next(cursor)
But this does not work, the result is 13 instead of 22. It seems that only c values have been summed, i.e. the $eq condition always returned false. How do you test that a field does not exist in an aggregation? I’ve read in the documentation (Query for Null or Missing Fields — MongoDB Manual) that testing the equality with None could mean that the field was affected to None or that the field did not exist. But the given examples only concerned search, not aggregation. Why is the behavior different?