检查 MongoDB 文档中是否存在多个字段 [英] Check for existence of multiple fields in MongoDB document

查看:43
本文介绍了检查 MongoDB 文档中是否存在多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to query a database collection that holds documents of processes for those documents that have specific fields. For simplicity imagine the following general document schema:

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

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

Now, when a process is started a new document is inserted with only the timestamp. When that process reaches certain stages the fields result1 and result2 are added over time. Some processes however do not reach the stages 1 or 2 and therefore have no result fields.

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

I would like to query the database to retrieve only those documents, which have BOTH result1 and result2.

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

I am aware of the $exists operator, but as far as I can tell this only works for one field at a time, i.e. db.coll.find({"result1": {$exists: true}}). The $exists operator cannot be used as a top level operator. E.g. this does not work:

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

要检查我需要的两个结果:

To check for both results I would need:

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

现在对于多个变量来说这已经变得乏味了.

Now that already becomes tedious for more than one variable.

有没有更好的方法来做到这一点?(另外,我正在用 Python 做这件事,所以如果有一个只针对 pymongo 驱动程序的解决方案会让我很高兴.)

Is there a better way to do this? (Also, I am doing this in Python, so if there is a solution for just the pymongo driver that would make me happy already.)

推荐答案

我不知道更好,但你总是可以通过 $where:

I don't know about better, but you can always process with JavaScript via $where:

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

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

但是您将不得不指定一组键"来检查某处.

But you are going to have to specify an array of "keys" to check for somewhere.

如果你认为你有很多键需要输入,那么为什么不构建"你的查询表达式:

If you think you have a lot of keys to type out, then why not just "build" your query expression:

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

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

coll.find(query)

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

That saves a bit of typing and since all MongoDB queries are just data structures anyway then using basic data manipulation to build queries makes sense.

这篇关于检查 MongoDB 文档中是否存在多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆