How to use the $regex Operator Directly In MongoDB
- $regex operator is used to search for the given string in the specified collection.If we use the regex operator directly in the find method then the find method return the matched document.
- It performs the case sensitive search without flag which returns the completely matched documents.
Syntax
db.collection.find({ key : { $regex: /value/ } })
Example
db.Student.find({favSub : {$regex:/maths/}});
Output:
Explanation: In the above example the w3wiki database contains the Student Collection with 3 document .From 3 documents 2 documents contains the maths as the favourite Subject (favSub field) but only one document is returned as we didn’t use any option or flag .If use regex operator directly is performs the case sensitive search.
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