How to use the $regex Operator with ‘i’ Flag In MongoDB
- $regex operator is used to search for the given string in the specified collection. To find a document with a specific value without considering the case, we use the regex operator with an i flag.
- The i flag is used to match both lower case and upper case patterns in the given document. We use the regex operator in the find() method to return the specific matched documents from the collection.
Syntax:
db.collection.find({ key : { $regex: /value/i } })
Or
db.collection.find({ key : { $regex : 'pattern', $options: ' $i' }})
Example:
In the example we are considering the w3wiki database with Student Collection. We have inserted three document with rollno,Name , favSub as the field values.
use w3wiki;
db.createCollection("Student");
db.Student.insertMany([{rollno:1,Name: "Jay",favSub:"Maths"},{rollno:2,Name :"Om", favSub: " maths"}, { rollno:3 ,Name : " Hari", favSub: "Science"}]);
We use regex operator with “i flag ” to perform case insensitive search.
db.Student.find({favSub : {$regex:/maths/i }});
Output:
Explanation: In the above example we perform case insensitive search to search the favSub with value “maths” as string. So, we pass a regular expression with search value with option(i.e., {$regex : /maths/i}) for the favSub field in the find() method. In the regular expression, i flag is used to match both lower case and upper case pattern in the document.
MongoDB Query with Case Insensitive Search
MongoDB, a leading NoSQL database, stores data in a flexible JSON-like format called BSON. In MongoDB, keys are stored as strings, and values can be strings, numbers, or objects. Sometimes there is a need to search for data without considering the case of the strings. This is where a case-insensitive search is needed.
In this article, we will explore how to perform case-insensitive searches in MongoDB using the $regex operator and the ‘i’ flag with the find() method in detail by understanding various methods along with the output and so on.
Contact Us