EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB like query
Secondary Sidebar
MongoDB Tutorial
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join

MongoDB like query

MongoDB like query

Introduction to MongoDB like query

Mongo db like the query is actually to search and match a specific pattern with the document records present in the Mongo DB database to retrieve or fetch only the specific fields or document records that match the specified pattern or regex or contain a particular character specified and hence satisfying the condition which ultimately filters out the result. SQL like query statement doesn’t exist in Mongo DB but we can make use of the alternative ways to implement the functionality similar to that as performed by the like query in SQL.

In this article, we will have a review about the usage of like query statement kind of functionality provided by SQL in MongoDB by trying the alternative solution to it and will also see the implementation of the same by considering the sample database and an example. The only prerequisite is that Mongo DB should be properly installed as well as configured on your machine.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Mongo DB like query by using find () function

In Mongo DB as we don’t have any query statement or clause like that of SQL LIKE, we can make use of the find () function which will help in providing similar functionality. We can search for a particular record, confirm the existence of such kind of record, or even perform a pattern matching by specifying the proper strings or regex or regular expressions for word and phrase matching which helps in retrieving only those records that will contain the specified string or part that is mentioned by us in the parameters of the find () function.

Syntax:

The findone () and find () functions are used in Mongo DB for implementing SQL-like functionality. The syntax of the find () syntax is as shown below.

db. collection. find (key-value pair(s) for matching)

In the above syntax as the find() is the method of the collection class of db, we have to give it a call using this format and the dot notation only.

Parameter – Also inside the brackets, we can optionally specify the key-value pairs specifying which key should contain what value or should satisfy what condition while finding the records from the document.

  • Return value – The find() function returns a cursor containing all the matched document records in it. We can further loop through this cursor to extract the result set and perform any further manipulation on the retrieved records if needed. This find() function automatically iterates the result set for the first 20 records for displaying them in its result set.
  • Optional parameters – There are also other two optional parameters that can be passed to the find() function which are query and the projection. Projection is used for specifying the fields to be retrieved for matching records. The default value of the projection parameter when not specified retrieves all the fields of the document. The query parameter is used for filtering the selection of the records to be scanned by the find() function.

Note: If you want to have an access to the result set returned by the find() function with a driver then, in that case, you will have to use for that particular driver language, a cursor handling mechanism to handle the result set.

Example

Let us firstly create a sample database shown below:

db.touristHillStations.insertMany([
{
hillStation: "Mahabaleshwar",
locationId: "MH456",
numberOfSpots: 100,
state: { city: "Satara", region: "POR" },
feedback: [
{ person: "Ronaldo", rating: 5 },
{ person: "Garry", rating: 4 }
] },
{
hillStation: "Lonavala",
locationId: "bts223",
numberOfSpots: 150,
state: { city: "Pune", region: "KHN" },
feedback: [
{ person: "Jenni", rating: 6 },
{ person: "Geeta", rating: 5 }
] },
{
hillStation: "Meghalaya",
locationId: "uhu963",
numberOfSpots: 180,
state: { city: "Himachal", region: "R543" },
feedback: [
{ person: "Rina", rating: 7 },
{ person: "Goerge", rating: 6 }
] },
{
hillStation: "Ooti",
locationId: "bds958",
numberOfSpots: 120,
state: { city: "Bangalore", region: "Res523" },
feedback: [
{ person: "Rahul", rating: 6 },
{ person: "Anju", rating: 6 }
] }
]);

The output of the execution of the above query statement for inserting the document records in MongoDB results in the following result shown in the below image.

monodb like query 1

Now, we will try to consider this sample database for querying through our like query kind off functionality demonstration in MongoDB with the help of find() function. First, of all let us try to retrieve the single record and confirm the contents of the MongoDB database by using the following query statement –

db.touristHillStations.findOne();

The output of the above query statement is as shown below –

monodb like query 2

As seen above the find() function returns a cursor. Now, let us try to use the find() function to implement the pattern matching functionality done by LIKE statement in SQL. We will do this by performing the slight modifications in the above query and mentioning the word or phrase, regex, or regular expression for matching the records. This will have the same behavior as that of the LIKE operator in the other relational databases such as SQL.
We will try to perform a query that will match the number of hill stations present in Pune city. For this, we should apply the filter on the city field and specify the regex with Pune name to get the total number of matching hill stations with Pune as the city. Our query statement will look as shown below –

db.touristHillStations.find({ "state.city": /Pune/ }).count();

The output of the execution of the above query statement will be as shown below retrieving the count as 1 because there is only one hill station located in Pune city as per the inserted sample database.

output 2

As shown in the above query statement we can make the changes in the string mentioned between the two forward slashes to specify a different string to be matched each time. We can also change the name of the field specified in the above example as a city to whichever field as per requirement.

Conclusion

We can implement the functionality of the like query in Mongo DB by using the find() function in the format – db.collection.find(). We can specify the string, regex, or regular expression for matching the values in the parameters of the find() function. The output is a cursor referencing the filtered document records.

Recommended Articles

This is a guide to MongoDB-like query. Here we discuss the Introduction, Mongo DB-like query by using find () function examples with code implementation respectively. You may also have a look at the following articles to learn more –

  1. MongoDB GridFS
  2. MongoDB Users
  3. MongoDB Relationships
  4. MongoDB Import
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (17 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (10 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more