

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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" }
- Related Questions & Answers
- Text search in MongoDB with Regular Expression
- MongoDB Regex Search on Integer Value?
- Implement Text search in MongoDB
- Perform MongoDB full text search
- Using regex in MongoDB findOne()
- Create an index for text search in MongoDB
- MongoDB $regex operator i or I for case insensitive search
- Avoid MongoDB performance issues while using regex
- Significance of regex match() and regex search() function in Python
- Adding default search text to search box in HTML with JavaScript?
- Search a string with special characters in a MongoDB document?
- Set regex in MongoDB $in?
- MongoDB query with case insensitive search?
- Search a value in an object with number keys with MongoDB
- How to search and replace text in a file using Python?
Advertisements