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" }

Updated on: 01-Apr-2020

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements