使用 PyMongo 执行正则表达式查询 [英] Performing regex queries with PyMongo
问题描述
我正在尝试使用 PyMongo 对 MongoDB 服务器执行正则表达式查询.文档结构如下
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"
}
我想获取所有与 *File.txt 匹配的文件.我试着这样做
I want to get all the files that match the pattern *File. I tried doing this as such
db.collectionName.find({'files':'/^File/'})
然而我什么也得不到.我是否遗漏了什么,因为根据 MongoDB 文档,这应该是可能的?如果我在 Mongo 控制台中执行查询它工作正常,这是否意味着 API 不支持它或者我只是使用它不正确?
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?
推荐答案
原来在 pymongo 中正则表达式搜索的方式略有不同,但同样简单.
Turns out regex searches are done a little differently in pymongo but is just as easy.
正则表达式如下:
db.collectionname.find({'files':{'$regex':'^File'}})
这将匹配所有具有 files 属性的文档,其中包含以 File 开头的项目
This will match all documents that have a files property that has a item within that starts with File
这篇关于使用 PyMongo 执行正则表达式查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!