Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 未定义数组的数组大小引发错误的投影_Mongodb_Aggregation Framework_Pymongo - Fatal编程技术网

Mongodb 未定义数组的数组大小引发错误的投影

Mongodb 未定义数组的数组大小引发错误的投影,mongodb,aggregation-framework,pymongo,Mongodb,Aggregation Framework,Pymongo,我正在努力做到以下几点: 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([{'$p

我正在努力做到以下几点:

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

最好的方法是与操作员联系

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