- 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
Using a regex with text search in MongoDB
To filter records using Regular Expression in MongoDB, use $regex. Let us first create a collection with documents −
> db.demo19.insertOne({"Values":"4321GH"}); { "acknowledged" : true, "insertedId" : ObjectId("5e1389b955d0fc6657d21f0f") } > db.demo19.insertOne({"Values":"12321_Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5e1389c755d0fc6657d21f10") } > db.demo19.insertOne({"Values":"8765Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e1389d355d0fc6657d21f11") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo19.find();
This will produce the following output −
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" } { "_id" : ObjectId("5e1389c755d0fc6657d21f10"), "Values" : "12321_Carol" } { "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" }
Here is the query to use regex with text search in MongoDB −
> db.demo19.find({Values: {$regex: /4321|8765/, $options: 'i'}});
This will produce the following output −
{ "_id" : ObjectId("5e1389b955d0fc6657d21f0f"), "Values" : "4321GH" } { "_id" : ObjectId("5e1389d355d0fc6657d21f11"), "Values" : "8765Mike" }
Advertisements