Query in MongoDB to perform an operation similar to LIKE operation


For similar operation, you can use / searchLetter /. Let us first create a collection with documents −

> db.demo26.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c9dc22d07d3b95082e79")
}
> db.demo26.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c9e022d07d3b95082e7a")
}
> db.demo26.insertOne({"StudentName":"Jones"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14ca7222d07d3b95082e7b")
}
> db.demo26.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14ca7622d07d3b95082e7c")
}

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

> db.demo26.find();

This will produce the following output −

{ "_id" : ObjectId("5e14c9dc22d07d3b95082e79"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName" : "John" }
{ "_id" : ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName" : "Jones" }
{ "_id" : ObjectId("5e14ca7622d07d3b95082e7c"), "StudentName" : "David" }

Following is the query to use the “LIKE” statement in MongoDB −

> db.demo26.find({"StudentName":/Jo/});

This will produce the following output -

{ "_id" : ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName" : "John" }
{ "_id" : ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName" : "Jones" }

Updated on: 02-Apr-2020

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements