Hello,
There is a way to check for field existence by using $ifNull expression explained here
It evaluates input expressions for null values, assigns a value if it’s null, in this case I assigned the value of “b” to be the value if “c” is null.
I tried your example in my testing environment and it produced the expected output of 22, please check the example below:
MongoDB Enterprise M040:PRIMARY> db.test.insertMany([{"a":5, "b":8}, {"a":3, "b":3, "c":4}, {"a":5, "b":1}, {"a":2, "b":7, "c":9}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("6352b73d645b4616bd7626b2"),
ObjectId("6352b73d645b4616bd7626b3"),
ObjectId("6352b73d645b4616bd7626b4"),
ObjectId("6352b73d645b4616bd7626b5")
]
}
MongoDB Enterprise M040:PRIMARY>
MongoDB Enterprise M040:PRIMARY> db.test.aggregate([
... {"$addFields": {"d": { $ifNull: [ "$c", "$b" ] }}},
... {"$group": {
... "_id": null,
... "total": {"$sum": "$d"},
... "count": {"$sum": 1}
... }}
... ])
{ "_id" : null, "total" : 22, "count" : 4 }
I hope you find this helpful.