Reputation:
I'm trying to do the following:
for i in range(5):
collection.insert({'a': ['1' for j in range(i)]} if i else {})
# the collection now contains 5 documents: one with only an _id field
# and four with an _id and an array of different sizes.]
list(m.aggregate([{'$project': {'a': 1, 'amt': {'$size': '$a'}}}]))
However, this throws an OperationFailure since $a isn't defined for the empty document.
How do I tell Mongo to give me a 0 for the empty document? Can I fall back to an empty array if field a
is undefined during projection?
Upvotes: 2
Views: 600
Reputation: 61253
The best way to do this is with the $ifNull
operator.
db.collection.aggregate([
{ "$project": {
"a": 1,
"amt": { "$size": { "$ifNull": [ "$a", [] ] } }
}}
])
Upvotes: 2
Reputation: 1696
You can check if the array exists (though not using $exists) and otherwise output 0, like so:
{
'$project': {
'a': 1,
'amt': {
$cond: [ {$gt: ["$a", null]}, {'$size': '$a'}, 0 ]
}
}
}
Upvotes: 1