Finding matching records with LIKE in MongoDB?

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents −

> db.likeDemo.insertOne({"Name":"John",Age:32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb84984623186894665ae41")
}
> db.likeDemo.insertOne({"Name":"Chris",Age:25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb84991623186894665ae42")
}
> db.likeDemo.insertOne({"Name":"Carol",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb849a1623186894665ae43")
}
> db.likeDemo.insertOne({"Name":"Johnny",Age:22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb849b2623186894665ae44")
}
> db.likeDemo.insertOne({"Name":"James",Age:27});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb849bb623186894665ae45")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cb84984623186894665ae41"),
   "Name" : "John",
   "Age" : 32
}
{
   "_id" : ObjectId("5cb84991623186894665ae42"),
   "Name" : "Chris",
   "Age" : 25
}
{
   "_id" : ObjectId("5cb849a1623186894665ae43"),
   "Name" : "Carol",
   "Age" : 22
}
{
   "_id" : ObjectId("5cb849b2623186894665ae44"),
   "Name" : "Johnny",
   "Age" : 22
}
{
   "_id" : ObjectId("5cb849bb623186894665ae45"),
   "Name" : "James",
   "Age" : 27
}

Following is the LIKE query in MongoDB displaying records beginning with Name “Jo” −

> db.likeDemo.find({Name: /^Jo/i } ).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cb84984623186894665ae41"),
   "Name" : "John",
   "Age" : 32
}
{
   "_id" : ObjectId("5cb849b2623186894665ae44"),
   "Name" : "Johnny",
   "Age" : 22
}
raja
Published on 30-Apr-2019 09:07:19
Advertisements