我正在运行下面的聚合函数。文档可能有也可能没有元素,我只想返回true / false。如果元素确实存在,则该元素是巨大的,因此返回整个元素会产生许多问题而不需要。
为了解决这个问题,我在版本3.0.4的生产环境中,并且升级到3.4目前不是一个选项,尽管看起来该版本有更好的解决方案。
为了测试这个,我在一个集合mycollection
中有一个文档。该文档有一个元素exists
,它是一个包含其他元素的对象。它没有名为notexists
的元素
db.runCommand({
"aggregate": "mycollection",
"pipeline": [{
"$match": {...}
}, {
"$sort": {...}
}, {
"$group": {...}
}, {
"$limit": 10
}, {
"$project": {
"aggregated": {
"$map": {
"input": "$mycollection",
"as": "document",
"in": {
"exists_test":{"$eq":["$$document.exists",null]},
"not_exists_test":{"$eq":["$$document.notexists",null]},
"exists_test_ifnull":{"$ifNull":["$$document.exists","test"]},
"not_exists_test_ifnull":{"$ifNull":["$$document.notexists","test"]},
"exists_content": "$$document.exists"
...
}
}
},
"success": {
"$cond": {
"if": { "$gt": ["$status", 0] },
"then": "false",
"else": "true"
}
}
}
}]
})
不幸的是,这会返回一个文档:
{
aggregated: [{
"exists_test": false, (correct)
"not_exists_test": false, (wrong)
"exists_test_ifnull": content from document.exists, (correct)
"not_exists_test_ifnull": "test", (correct)
"exists_content": content from document.exists, (correct)
}]
}
似乎"not_exists_test":{"$eq":["$$document.notexists",null]},
应该返回true,因为$ifNull
确实反映了该值为null。
尝试"not_exists_test": { "$gt": ["$$document.notexists", null] }
,如BSON types comparison order所暗示的那样。
对于Mongodb 3.2,它适用于单个$符号,
"not_exists_test": { "$gt": ["$document.notexists", null] }