mongodb 使用 pymongo 执行正则表达式查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3483318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:46:56  来源:igfitidea点击:

Performing regex Queries with pymongo

mongodbpymongo

提问by RC1140

I am trying to perform a regex query using pymongo against a mongodb server. The document structure is as follows

我正在尝试使用 pymongo 对 mongodb 服务器执行正则表达式查询。文档结构如下

{
  "files": [
    "File 1",
    "File 2",
    "File 3",
    "File 4"
  ],
  "rootFolder": "/Location/Of/Files"
}

I want to get all the files that match the pattern *File. I tried doing this as such

我想获取所有与 *File.txt 匹配的文件。我试着这样做

db.collectionName.find({'files':'/^File/'})

Yet i get nothing back , am i missing something because according to the mongodb docs this should be possible. If I perform the query in the mongo console it works fine , does this mean the api doesnt support it or am I just using it incorrectly

然而我什么也没得到,我是不是遗漏了什么,因为根据 mongodb 文档,这应该是可能的。如果我在 mongo 控制台中执行查询它工作正常,这是否意味着 api 不支持它或者我只是使用它不正确

回答by Eric

If you want to include regular expression options (such as ignore case), try this:

如果要包含正则表达式选项(例如忽略大小写),请尝试以下操作:

import re
regx = re.compile("^foo", re.IGNORECASE)
db.users.find_one({"files": regx})

回答by RC1140

Turns out regex searches are done a little differently in pymongo but is just as easy.

事实证明,在 pymongo 中正则表达式搜索的完成方式略有不同,但同样简单。

Regex is done as follows :

正则表达式完成如下:

db.collectionname.find({'files':{'$regex':'^File'}})

This will match all documents that have a files property that has a item within that starts with File

这将匹配具有 files 属性的所有文档,其中包含以 File 开头的项目

回答by Keeely

To avoid the double compilation you can use the bson regex wrapper that comes with PyMongo:

为了避免双重编译,您可以使用 PyMongo 附带的 bson regex 包装器:

>>> regx = bson.regex.Regex('^foo')
>>> db.users.find_one({"files": regx})

Regex just stores the string without trying to compile it, so find_one can then detect the argument as a 'Regex' type and form the appropriate Mongo query.

Regex 只是存储字符串而不尝试编译它,因此 find_one 可以将参数检测为“Regex”类型并形成适当的 Mongo 查询。

I feel this way is slightly more Pythonic than the other top answer, e.g.:

我觉得这种方式比其他最佳答案更 Pythonic,例如:

>>> db.collectionname.find({'files':{'$regex':'^File'}})

It's worth reading up on the bson Regex documentation if you plan to use regex queries because there are some caveats.

如果您打算使用正则表达式查询,那么值得阅读 bson Regex 文档,因为有一些注意事项。

回答by Jeff

The solution of redoesn't use the index at all. You should use commands like:

的解决方案re根本不使用索引。您应该使用以下命令:

db.collectionname.find({'files':{'$regex':'^File'}})

db.collectionname.find({'files':{'$regex':'^File'}})

( I cannot comment below their replies, so I reply here )

(我不能在他们的回复下面发表评论,所以我在这里回复)