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
Is it possible to use MongoDB field value as a pattern in $regex?
Yes, you can use a MongoDB field value as a pattern in $regex using the $expr operator. However, the most practical approach is using $indexOfCP to check if one field value exists within another field.
Syntax
db.collection.aggregate([
{
"$match": {
"$expr": {
"$ne": [
{ "$indexOfCP": ["$fieldToSearch", "$patternField"] },
-1
]
}
}
}
])
Sample Data
db.demo88.insertMany([
{
"Name": "Chris",
"PassoutYear": "2020",
"websiteName": "chris.shop.com/Carol-2020-"
},
{
"Name": "David",
"PassoutYear": "2010",
"websiteName": "david.bigshop.com/David-2010-"
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e2c14c471bf0181ecc422b1"),
"1": ObjectId("5e2c14c571bf0181ecc422b2")
}
}
Example: Field Value as Pattern
Find documents where the Name field value exists within the websiteName field ?
db.demo88.aggregate([
{
"$match": {
"$expr": {
"$ne": [
{ "$indexOfCP": ["$websiteName", "$Name"] },
-1
]
}
}
}
])
{ "_id": ObjectId("5e2c14c571bf0181ecc422b2"), "Name": "David", "PassoutYear": "2010", "websiteName": "david.bigshop.com/David-2010-" }
How It Works
-
$indexOfCPsearches for theNamefield value within thewebsiteNamefield - Returns the index position if found, or
-1if not found -
$ne: -1filters documents where the pattern was found (index ? -1) - Only "David" matches because "David" exists in "david.bigshop.com/David-2010-"
Conclusion
While MongoDB doesn't directly support field values in $regex, $indexOfCP with $expr provides an effective alternative for pattern matching using field values. This approach is more efficient than complex regex operations.
Advertisements
