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
How do I make case-insensitive queries on MongoDB?
To make case-insensitive queries in MongoDB, use regular expressions with the i flag or the $regex operator. This allows you to match documents regardless of letter case variations.
Syntax
// Method 1: Regular Expression with i flag
db.collection.find({ "field": /pattern/i });
// Method 2: $regex operator
db.collection.find({ "field": { $regex: "pattern", $options: "i" } });
Sample Data
db.caseInsensitiveDemo.insertMany([
{"UserName": "David"},
{"UserName": "DAVID"},
{"UserName": "david"},
{"UserName": "Carol"},
{"UserName": "Mike"},
{"UserName": "Sam"},
{"UserName": "daVID"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c7f6fec8d10a061296a3c45"),
ObjectId("5c7f6ff28d10a061296a3c46"),
ObjectId("5c7f6ffa8d10a061296a3c47"),
ObjectId("5c7f70008d10a061296a3c48"),
ObjectId("5c7f70058d10a061296a3c49"),
ObjectId("5c7f70098d10a061296a3c4a"),
ObjectId("5c7f70138d10a061296a3c4b")
]
}
Method 1: Using Regular Expression
Find all variations of "david" regardless of case ?
db.caseInsensitiveDemo.find({UserName: /^david$/i });
{ "_id": ObjectId("5c7f6fec8d10a061296a3c45"), "UserName": "David" }
{ "_id": ObjectId("5c7f6ff28d10a061296a3c46"), "UserName": "DAVID" }
{ "_id": ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName": "david" }
{ "_id": ObjectId("5c7f70138d10a061296a3c4b"), "UserName": "daVID" }
Method 2: Using $regex Operator
Alternative syntax using the $regex operator ?
db.caseInsensitiveDemo.find({
"UserName": { $regex: "^david$", $options: "i" }
});
{ "_id": ObjectId("5c7f6fec8d10a061296a3c45"), "UserName": "David" }
{ "_id": ObjectId("5c7f6ff28d10a061296a3c46"), "UserName": "DAVID" }
{ "_id": ObjectId("5c7f6ffa8d10a061296a3c47"), "UserName": "david" }
{ "_id": ObjectId("5c7f70138d10a061296a3c4b"), "UserName": "daVID" }
Key Points
- The
iflag makes the regex case-insensitive -
^and$ensure exact match (start and end of string) - Both methods produce identical results
- Regular expressions are slower than exact matches, so use indexes when possible
Conclusion
MongoDB supports case-insensitive queries through regular expressions with the i flag or the $regex operator. Use ^pattern$ for exact matches and just pattern for partial matches.
Advertisements
