使用 PyMongo 执行 regex 查询?
PyMongo 是一个 Python 发行版,包含用于操作 MongoDB 的工具。要使用 PyMongo 执行 regex 查询,语法如下 −
db.yourCollectionName.find({'yourCollectionName':{'$regex':'^yourWords'}}).pretty();
以上语法会给出从特定词语开头的所有文档。
为了理解该语法,让我们使用文档创建一个集合。创建带有文档的集合的查询如下 −
> db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[ "Folder 1","Folder 2","Folder 3","Folder 4","Folder 5"], "MainFolderLocation":"/MainFolder/Details/ClientFolder" }); { "acknowledged" : true, "insertedId" : ObjectId("5c8a8b186cea1f28b7aa07f2") } > db.performRegex.insertOne({"ClientName":"Larry","ClientFolderInformation":[ "ClientFolder 1","ClientFolder 2","ClientFolder 3","ClientFolder 4","ClientFolder 5"], "MainFolderLocation":"/MainFolder/Details/ClientFolder" }); { "acknowledged" : true, "insertedId" : ObjectId("5c8a8b1d6cea1f28b7aa07f3") }
通过 find() 方法显示来自集合的所有文档。查询如下 −
> db.performRegex.find().pretty();
以下是输出 −
{ "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"), "ClientName" : "Larry", "ClientFolderInformation" : [ "Folder 1", "Folder 2", "Folder 3", "Folder 4", "Folder 5" ], "MainFolderLocation" : "/MainFolder/Details/ClientFolder" } { "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"), "ClientName" : "Larry", "ClientFolderInformation" : [ "ClientFolder 1", "ClientFolder 2", "ClientFolder 3", "ClientFolder 4", "ClientFolder 5" ], "MainFolderLocation" : "/MainFolder/Details/ClientFolder" }
以下是执行正则表达式的查询。
用例 1 − 下面的查询会给出以单词“ClientFolder”开头的所有文档 −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^ClientFolder'}}).pretty();
以下是输出 −
{ "_id" : ObjectId("5c8a8b1d6cea1f28b7aa07f3"), "ClientName" : "Larry", "ClientFolderInformation" : [ "ClientFolder 1", "ClientFolder 2", "ClientFolder 3", "ClientFolder 4", "ClientFolder 5" ], "MainFolderLocation" : "/MainFolder/Details/ClientFolder" }
用例 2 − 下面的查询会给出以单词“Folder”开头的所有文档 −
> db.performRegex.find({'ClientFolderInformation':{'$regex':'^Folder'}}).pretty();
以下是输出 −
{ "_id" : ObjectId("5c8a8b186cea1f28b7aa07f2"), "ClientName" : "Larry", "ClientFolderInformation" : [ "Folder 1", "Folder 2", "Folder 3", "Folder 4", "Folder 5" ], "MainFolderLocation" : "/MainFolder/Details/ClientFolder" }
广告