Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding matching records with LIKE in MongoDB?
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
}Advertisements