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
Regex to ignore a specific character in MongoDB?
To ignore a specific character in MongoDB, use regular expressions with either the $not operator or character negation patterns. These approaches filter out documents containing the unwanted character.
Syntax
// Method 1: Using character negation
db.collection.find({field: /^[^CHARACTER]*$/});
// Method 2: Using $not operator
db.collection.find({field: {$not: /CHARACTER/}});
Sample Data
db.regexDemo.insertMany([
{"CustomerId": "Customer#1234", "CustomerName": "Chris"},
{"CustomerId": "Customer5678", "CustomerName": "Robert"},
{"CustomerId": "Customer#777", "CustomerName": "Carol"},
{"CustomerId": "Customer777", "CustomerName": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc7428f8f9e6ff3eb0ce436"),
ObjectId("5cc7429e8f9e6ff3eb0ce437"),
ObjectId("5cc742ae8f9e6ff3eb0ce438"),
ObjectId("5cc742bc8f9e6ff3eb0ce439")
]
}
Method 1: Using Character Negation
Find all documents where CustomerId does not contain the # character ?
db.regexDemo.find({CustomerId: /^[^#]*$/});
{
"_id": ObjectId("5cc7429e8f9e6ff3eb0ce437"),
"CustomerId": "Customer5678",
"CustomerName": "Robert"
}
{
"_id": ObjectId("5cc742bc8f9e6ff3eb0ce439"),
"CustomerId": "Customer777",
"CustomerName": "David"
}
Method 2: Using $not Operator
Alternative approach using the $not operator to exclude documents containing # ?
db.regexDemo.find({CustomerId: {$not: /#/}});
{
"_id": ObjectId("5cc7429e8f9e6ff3eb0ce437"),
"CustomerId": "Customer5678",
"CustomerName": "Robert"
}
{
"_id": ObjectId("5cc742bc8f9e6ff3eb0ce439"),
"CustomerId": "Customer777",
"CustomerName": "David"
}
Key Differences
-
/^[^#]*$/matches strings that contain only characters other than# -
{$not: /#/}excludes any string that contains the#character anywhere - Both methods produce the same result for this use case
Conclusion
Use regex patterns with $not operator or character negation [^CHARACTER] to filter out documents containing specific characters. The $not approach is more readable and straightforward for simple character exclusions.
Advertisements
