Build (escape) regexp in MongoDB?

MongoDBDatabaseBig Data Analytics

For this, use find() along with //i. Let us create a collection with documents −

> db.demo696.insertOne({Message:"/Good/"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d664551299a9f98c9391")
}
> db.demo696.insertOne({Message:"(good)"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d67a551299a9f98c9392")
}
> db.demo696.insertOne({Message:"/Bye/"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d68b551299a9f98c9393")
}
> db.demo696.insertOne({Message:"(GOOD)"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d693551299a9f98c9394")
}

Display all documents from a collection with the help of find() method −

> db.demo696.find();

This will produce the following output −

{ "_id" : ObjectId("5ea6d664551299a9f98c9391"), "Message" : "/Good/" }
{ "_id" : ObjectId("5ea6d67a551299a9f98c9392"), "Message" : "(good)" }
{ "_id" : ObjectId("5ea6d68b551299a9f98c9393"), "Message" : "/Bye/" }
{ "_id" : ObjectId("5ea6d693551299a9f98c9394"), "Message" : "(GOOD)" }

Following is the query to escape regexp −

> db.demo696.find({Message:/good/i});

This will produce the following output −

{ "_id" : ObjectId("5ea6d664551299a9f98c9391"), "Message" : "/Good/" }
{ "_id" : ObjectId("5ea6d67a551299a9f98c9392"), "Message" : "(good)" }
{ "_id" : ObjectId("5ea6d693551299a9f98c9394"), "Message" : "(GOOD)" }
raja
Published on 14-May-2020 09:23:39
Advertisements