How to query MongoDB similar to “like” ?


To implement similar to “like”, use find() along with // in MongoDB. Let us create a collection with documents −

> db.demo686.insertOne({"FirstName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea55182a7e81adc6a0b395c")
}
> db.demo686.insertOne({"FirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea55186a7e81adc6a0b395d")
}
> db.demo686.insertOne({"FirstName":"ROBERT"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea5518fa7e81adc6a0b395e")
}
> db.demo686.insertOne({"FirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea55195a7e81adc6a0b395f")
}
> db.demo686.insertOne({"FirstName":"robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea5519ba7e81adc6a0b3960")
}

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

> db.demo686.find();

This will produce the following output −

{ "_id" : ObjectId("5ea55182a7e81adc6a0b395c"), "FirstName" : "Robert" }
{ "_id" : ObjectId("5ea55186a7e81adc6a0b395d"), "FirstName" : "John" }
{ "_id" : ObjectId("5ea5518fa7e81adc6a0b395e"), "FirstName" : "ROBERT" }
{ "_id" : ObjectId("5ea55195a7e81adc6a0b395f"), "FirstName" : "David" }
{ "_id" : ObjectId("5ea5519ba7e81adc6a0b3960"), "FirstName" : "robert" }

Following is the query similar to “like” −

> db.demo686.find({FirstName:/Robert/i});

This will produce the following output −

{ "_id" : ObjectId("5ea55182a7e81adc6a0b395c"), "FirstName" : "Robert" }
{ "_id" : ObjectId("5ea5518fa7e81adc6a0b395e"), "FirstName" : "ROBERT" }
{ "_id" : ObjectId("5ea5519ba7e81adc6a0b3960"), "FirstName" : "robert" }

Updated on: 14-May-2020

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements