Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Performing regex Queries with PyMongo?
PyMongo is a Python distribution containing tools for working with MongoDB. To perform regex queries with PyMongo, you use the $regex operator to match documents where field values match a specified regular expression pattern.
Syntax
db.collection.find({
"fieldName": {
"$regex": "pattern",
"$options": "flags"
}
})
Sample Data
Let us create a collection with sample documents ?
db.performRegex.insertMany([
{
"ClientName": "Larry",
"ClientFolderInformation": [
"Folder 1", "Folder 2", "Folder 3", "Folder 4", "Folder 5"
],
"MainFolderLocation": "/MainFolder/Details/ClientFolder"
},
{
"ClientName": "Larry",
"ClientFolderInformation": [
"ClientFolder 1", "ClientFolder 2", "ClientFolder 3", "ClientFolder 4", "ClientFolder 5"
],
"MainFolderLocation": "/MainFolder/Details/ClientFolder"
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8a8b186cea1f28b7aa07f2"),
ObjectId("5c8a8b1d6cea1f28b7aa07f3")
]
}
Case 1: Find Array Elements Starting with "ClientFolder"
Find documents where array elements start with "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"
}
Case 2: Find Array Elements Starting with "Folder"
Find documents where array elements start with "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"
}
PyMongo Implementation
Here's how to perform the same regex queries using PyMongo in Python ?
from pymongo import MongoClient
import re
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['performRegex']
# Method 1: Using $regex operator
result = collection.find({
"ClientFolderInformation": {
"$regex": "^ClientFolder"
}
})
# Method 2: Using Python's re module
result = collection.find({
"ClientFolderInformation": re.compile("^ClientFolder")
})
Conclusion
The $regex operator enables pattern matching in MongoDB queries. Use ^ for start-of-string matching and combine with PyMongo for powerful text search capabilities in Python applications.
Advertisements
