user4673965
user4673965

Reputation:

Projection from array size throwing error for undefined array

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

Answers (2)

Sede
Sede

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

Wake
Wake

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

Related Questions