Updated March 8, 2023
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.
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.
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 –
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.
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 –