- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use $regex in MongoDB?
Following is the syntax to use $regex in MongoDB −
db.yourCollectionName.find({yourFieldName: { $regex: yourValue}});
Let us first create a collection with documents −
> db.regularExpressionDemo.insertOne({"UserName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5cdffc25bf3115999ed51210") } > db.regularExpressionDemo.insertOne({"UserName":"JOHN"}); { "acknowledged" : true, "insertedId" : ObjectId("5cdffc2ebf3115999ed51211") } > db.regularExpressionDemo.insertOne({"UserName":"john"}); { "acknowledged" : true, "insertedId" : ObjectId("5cdffc35bf3115999ed51212") } > db.regularExpressionDemo.insertOne({"UserName":"JoHn"}); { "acknowledged" : true, "insertedId" : ObjectId("5cdffc3ebf3115999ed51213") }
Following is the query to display all documents from a collection with the help of find() method −
> db.regularExpressionDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" } { "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" } { "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" } { "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
Following is the query to use $regex −
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN'}});
This will produce the following output −
{ "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" }
Let us now match all the cases. Following is the query −
> db.regularExpressionDemo.find({'UserName': { $regex: 'JOHN', $options: 'i' }});
This will produce the following output −
{ "_id" : ObjectId("5cdffc25bf3115999ed51210"), "UserName" : "John" } { "_id" : ObjectId("5cdffc2ebf3115999ed51211"), "UserName" : "JOHN" } { "_id" : ObjectId("5cdffc35bf3115999ed51212"), "UserName" : "john" } { "_id" : ObjectId("5cdffc3ebf3115999ed51213"), "UserName" : "JoHn" }
Advertisements