检查 MongoDB 文档中是否存在多个字段

Check for existence of multiple fields in MongoDB document

我正在尝试查询一个数据库集合,该集合包含具有特定字段的那些文档的流程文档。为简单起见,想象以下通用文档架构:

{
    "timestamp": ISODate("..."),
    "result1": "pass",
    "result2": "fail"
}

现在,当一个进程启动时,一个新文档被插入,只有时间戳。当该过程达到某些阶段时,字段 result1result2 会随着时间的推移添加。但是,某些进程未达到 12 阶段,因此没有结果字段。

我想查询数据库以仅检索那些同时具有 result1result2 的文档。

我知道 $exists 运算符,但据我所知,它一次只能用于一个字段,即 db.coll.find({"result1": {$exists: true}})$exists 运算符不能用作顶级运算符。例如。这有效:

db.coll.find({"$exists": {"result1": true, "result2": true}})

要检查这两个结果,我需要:

db.coll.find({"result1": {"$exists": true}, "result2": {"$exists": true}})

现在对于不止一个变量来说已经变得乏味了。

有更好的方法吗? (另外,我在 Python 中这样做,所以如果有一个只针对 pymongo 驱动程序的解决方案会让我很高兴。)

我不知道更好的方法,但您始终可以通过 $where 使用 JavaScript 进行处理:

jsStr = """var doc = this;
           return ['result1','result2','result3']
           .every(function(key) { 
               return doc.hasOwnProperty(key) 
           });"""

coll.find({ "$where": jsStr })

但是您将必须指定一个 "keys" 的数组来检查某处。

如果您认为要输入很多键,那么为什么不 "build" 您的查询表达式:

whitelist = [ "result1", "result2", "result3" ]
query = {}

for key in whitelist:
    query[key] = { "$exists": True }

coll.find(query)

这节省了一些输入,而且由于所有 MongoDB 查询无论如何都只是数据结构,因此使用基本数据操作来构建查询是有意义的。

如何使用$and:

db.coll.find({"$and": [                                                                     
            { "fld1": { "$exists": true }}                                              
            , { "fld2": { "$exists": true }}                                            
            , { "fld3": { "$exists": true }}                                            
]})