How to use the $regex Operator with Variable In MongoDB
- $regex operator is used to search for the given string in the specified collection.We can pass a variable to regex operator to search for the particular value.
- To pass a variable we use RegExp() constructor which is used to perform pattern matching. Along with a variable we can also pass a flags. If we pass i flag then it is used to match both lower case and upper case pattern in the given document.
- We use the regex operator in the find() method to return the specific matched documents from the collection.
db.Student.find({ favSub: { $regex: new RegExp(subject, 'i') } });
Output:
Explanation: In the above example we use $regex operator along with a variable to perform the pattern matching .Inially subject variable is assigned the “Maths” value.Then the variable is passed in the RegExp() constructor along with the “i” flag to perform the case-insensitive search.As the collection contains two documents with favSub field with “maths” as value they are returned as output.
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.