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

编程入门 行业动态 更新时间:2024-10-24 06:25:17
本文介绍了检查 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" }

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

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.

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

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 文档中是否存在多个字段

本文发布于:2023-11-22 18:39:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618555.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字段   是否存在   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!