未定义数组的数组大小投影抛出错误

Projection from array size throwing error for undefined array

我正在尝试执行以下操作:

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'}}}]))

但是,这会引发 OperationFailure,因为没有为空文档定义 $a。

如何告诉 Mongo 为空文档给我一个 0?如果字段 a 在投影期间未定义,我可以回退到空数组吗?

你可以检查数组是否存在(尽管不使用 $exists)否则输出 0,像这样:

{
    '$project': {
        'a': 1, 
        'amt': {
            $cond: [ {$gt: ["$a", null]}, {'$size': '$a'}, 0 ]
        }
    }
}

最好的方法是使用 $ifNull 运算符。

db.collection.aggregate([
    { "$project": {
        "a": 1, 
        "amt": { "$size": { "$ifNull": [ "$a", [] ] } }
    }}
])