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

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" }
Updated on: 2019-07-30T22:30:26+05:30

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements