如果使用mongodb$map的文档中存在元素,如何返回true/false?
我正在运行下面的聚合函数。文档可能有也可能没有元素,我只想返回true/false。如果元素确实存在,那么它是巨大的,因此返回整个元素会产生许多问题,因此不需要 为了解决这个问题,我在3.0.4版的生产环境中,目前还不能升级到3.4版,尽管看起来该版本有更好的解决方案 为了测试这一点,我在一个集合如果使用mongodb$map的文档中存在元素,如何返回true/false?,mongodb,Mongodb,我正在运行下面的聚合函数。文档可能有也可能没有元素,我只想返回true/false。如果元素确实存在,那么它是巨大的,因此返回整个元素会产生许多问题,因此不需要 为了解决这个问题,我在3.0.4版的生产环境中,目前还不能升级到3.4版,尽管看起来该版本有更好的解决方案 为了测试这一点,我在一个集合mycollection中有一个文档。文档中有一个元素exists,它是一个包含其他元素的对象。它没有名为notexists的元素 db.runCommand({ "aggregate": "m
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\u exists\u test”:{“$eq”:[“$$document.notexists”,null]},
应该返回true,因为$ifNull
确实准确地反映了该值为null。尝试“not\u exists\u test”:{“$gt”:[“$$document notexists”,null]}
,正如.p>对于Mongodb 3.2,它使用单个$符号
"not_exists_test": { "$gt": ["$document.notexists", null] }
请尝试“not\u exists\u test”:{“$gt”:[“$$document.notexists”,null]},
,如中所示。!!明亮的那很好用。谢谢加上它作为答案,我会把它标对的。