使用 PyMongo 执行正则表达式查询
我正在尝试使用 PyMongo 对 MongoDB 服务器执行正则表达式查询。文档结构如下
{
"files": [
"File 1",
"File 2",
"File 3",
"File 4"
],
"rootFolder": "/Location/Of/Files"
}
我想获取与模式*File匹配的所有文件。我尝试这样做,
db.collectionName.find({'files':'/^File/'})
但我什么也没得到。我是否遗漏了一些东西,因为根据 MongoDB 文档,这应该是可能的?如果我在 Mongo 控制台中执行查询,它工作正常,这是否意味着 API 不支持它,或者我只是错误地使用了它?
I am trying to perform a regex query using PyMongo against a MongoDB server. The document structure is as follows
{
"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
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 doesn't support it or am I just using it incorrectly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想包含正则表达式选项(例如忽略大小写),请尝试以下操作:
If you want to include regular expression options (such as ignore case), try this:
事实证明,正则表达式搜索在 pymongo 中的执行方式略有不同,但同样简单。
正则表达式的完成方式如下:
这将匹配具有 files 属性且其中包含以 File 开头的项目的所有文档
Turns out regex searches are done a little differently in pymongo but is just as easy.
Regex is done as follows :
This will match all documents that have a files property that has a item within that starts with File
为了避免双重编译,您可以使用 PyMongo 附带的 bson regex 包装器:
Regex 只是存储字符串而不尝试编译它,因此 find_one 然后可以将参数检测为“Regex”类型并形成适当的 Mongo 查询。
我觉得这种方式比其他最佳答案更Pythonic,例如:
如果您打算使用正则表达式查询,那么值得阅读bson正则表达式文档,因为有一些警告。
To avoid the double compilation you can use the bson regex wrapper that comes with PyMongo:
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.
I feel this way is slightly more Pythonic than the other top answer, e.g.:
It's worth reading up on the bson Regex documentation if you plan to use regex queries because there are some caveats.
re
的解决方案根本不使用索引。您应该使用如下命令:
db.collectionname.find({'files':{'$regex':'^File'}})
(我无法在他们的回复下面发表评论,所以我在这里回复)
The solution of
re
doesn't use the index at all.You should use commands like:
db.collectionname.find({'files':{'$regex':'^File'}})
( I cannot comment below their replies, so I reply here )