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", [] ] } }
}}
])