What is the equivalent of SQL “like” in MongoDB?


You can use “$regex” operator to implement the equivalent of SQL ‘like’ in MongoDB. To implement it, let us create a collection with a document. The query to create a collection with a document is as follows −

> db.sqlLikeDemo.insertOne({"UserName":"John Smith","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e124afe5c1d2279d6a5")
}
> db.sqlLikeDemo.insertOne({"UserName":"John Doe","UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e264afe5c1d2279d6a6")
}
> db.sqlLikeDemo.insertOne({"UserName":"Chris Williams","UserAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e404afe5c1d2279d6a7")
}
> db.sqlLikeDemo.insertOne({"UserName":"Robert Taylor","UserAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e4d4afe5c1d2279d6a8")
}
> db.sqlLikeDemo.insertOne({"UserName":"John Brown","UserAge":27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e6c4afe5c1d2279d6a9")
}
> db.sqlLikeDemo.insertOne({"UserName":"Mike Brown","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e794afe5c1d2279d6aa")
}
> db.sqlLikeDemo.insertOne({"UserName":"Larry Smith","UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c912e8c4afe5c1d2279d6ab")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c912e124afe5c1d2279d6a5"),
   "UserName" : "John Smith",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c912e264afe5c1d2279d6a6"),
   "UserName" : "John Doe",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c912e404afe5c1d2279d6a7"),
   "UserName" : "Chris Williams",
   "UserAge" : 22
}
{
   "_id" : ObjectId("5c912e4d4afe5c1d2279d6a8"),
   "UserName" : "Robert Taylor",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"),
   "UserName" : "John Brown",
   "UserAge" : 27
}
{
   "_id" : ObjectId("5c912e794afe5c1d2279d6aa"),
   "UserName" : "Mike Brown",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c912e8c4afe5c1d2279d6ab"),
   "UserName" : "Larry Smith",
   "UserAge" : 24
}

Here is the query that works like SQL ‘like’ clause i.e. the record with “UserName” John −

> db.sqlLikeDemo.find({"UserName":{"$regex": "John"}}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c912e124afe5c1d2279d6a5"),
   "UserName" : "John Smith",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c912e264afe5c1d2279d6a6"),
   "UserName" : "John Doe",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"),
   "UserName" : "John Brown",
   "UserAge" : 27
}

Updated on: 30-Jul-2019

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements