What should be used to implement MySQL LIKE statement in MongoDB?


To get MySQL LIKE statement, use the REGEX in MongoDB. Let us first create a collection with documents −

> db.likeInMongoDBDemo.insertOne({"Name" : "Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6922857806ebf1256f123")
}
> db.likeInMongoDBDemo.insertOne({"Name" : "John" });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6923157806ebf1256f124")
}
> db.likeInMongoDBDemo.insertOne({"Name" : "Scott"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6924557806ebf1256f125")
}
> db.likeInMongoDBDemo.insertOne({"Name" : "Sean"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6924f57806ebf1256f126")
}
> db.likeInMongoDBDemo.insertOne({"Name" : "Samuel"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd6925857806ebf1256f127")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.likeInMongoDBDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cd6922857806ebf1256f123"), "Name" : "Sam" }
{ "_id" : ObjectId("5cd6923157806ebf1256f124"), "Name" : "John" }
{ "_id" : ObjectId("5cd6924557806ebf1256f125"), "Name" : "Scott" }
{ "_id" : ObjectId("5cd6924f57806ebf1256f126"), "Name" : "Sean" }
{ "_id" : ObjectId("5cd6925857806ebf1256f127"), "Name" : "Samuel" }

Following is the query to perform REGEX to match the MySQL LIKE statement in MongoDB −

> db.likeInMongoDBDemo.find({"Name":{$regex:"Sam"}});

This will produce the following output −

{ "_id" : ObjectId("5cd6922857806ebf1256f123"), "Name" : "Sam" }
{ "_id" : ObjectId("5cd6925857806ebf1256f127"), "Name" : "Samuel" }
raja
Published on 13-Jun-2019 11:24:13
Advertisements