In this section, we will try to understand how to query the collections on MongoDB and it is expected that you have the basic knowledge of how to install, connect, and insert data into MongoDB. Now with the expectation set properly, it is the time to get neck-deep into how to query your documents that are inserted into your collections.
We have used MongoDB version v3.4.7 while this article was written and the entirety of the article might not 100% work if you are using any different version of MongoDB.
The DML (data manipulation) commands for MongoDB are provided in a synonymic way. Let us understand once the data is available in the form of documents in MongoDB, how can execute these commands (as shown below), to help us find them and apply data manipulation operations on the resultant result set.
If you want to enrich your career and become a professional in MongoDB, then visit Mindmajix - a global online training platform: "MongoDB Online Training" This course will help you to achieve excellence in this domain.
For us to discuss more on the find() methods that are made available for the MongoDB database server, we have set up a sample database and a collection with few documents already. We will try to see how each of them find() methods available with MongoDB that can be used to query the documents of a collection.
We will also see how to manipulate the data once we find what we need to find. Considering that, please follow the following screenshot for a command to insert some dummy data.
[Related Article: What is MongoDB]
With the data available, we will see the first find() method. Syntax and usage will be explained along with a comparison of this query in MongoDB against the RDBMS way of querying tables.
All the topics mentioned above can be achieved by using just one command, using the find() command on the Collection of your choice. Please follow the section below where we try to explain this in more detail.
Syntax: db.SampleCollection.find()
RDBMS Syntax: SELECT * FROM SampleCollection
The syntax is shown as above and also the screenshot should be self-explanatory, as this is a plain old SELECT query without having a WHERE clause in the RDBMS scenario. The same can be replicated in the MongoDB database context as find() with no query parameters given as input to the command.
So as you can see below, we have got all the 5 rows as output to the command above.
The above command shows the usage of the find() method on MongoDB where there is no query parameter provided, that is indirect to execute a query on the Collection to return all the documents from it. If we were to retrieve just the documents from the documents only.
[Related Article: Sort MongoDB]
Please follow the details on how to achieve this from the following: collection matching a certain condition, then we might have to provide the find() method the condition to retrieve those specific.
Syntax: db.SampleCollection.find({ studentGrade : “A”})
RDBMS Syntax: SELECT * FROM SampleCollection WHERE studentGrade = “A”
The result is shown below in the screenshot:
MongoDB find one
MongoDB find by ID
MongoDB find like
This section deals with the next command provided by MongoDB, which is the findOne() method. The syntax of this method is very similar to that we have seen for find() method, but with only one difference. The output of this command is always just documented from the collection if the condition returns more than one document.
Checkout Our Frequently Asked MongoDB Interview Questions For Experienced
Syntax: db.SampleCollection.findOne( { studentGroup : “MPC” })
RDBMS Syntax: SELECT * FROM SampleCollection
WHERE studentGroup = “MPC” LIMIT 1
The findOne() method expects a query condition to be provided based on the Collection on which this query is being executed. If the result set contains more than one document to be presented, it would pick the first document as the result instead of all the matching results.
If the query needs to be understood in an RDBMS way, this is equivalent to running a SELECT query on a specific table with a WHERE clause on a specific column limiting the result set to return just one single row.
[Related Article: Learn MongoDB]
The example above was returning all the fields from the document, but we can control the fields that we select from the documents as such. This can be achieved by providing the projection clause in the find() method itself.
You would have observed though we have not mentioned the _id column as part of the Projection clause, it gets selected and is shown aptly in the RDBMS equivalent syntax – this is by definition the design of MongoDB.
MongoDB find and modify
MongoDB find and update
MongoDB find one and update
This section of the article discusses the next command provided by MongoDB, which is used to find a specific document from the collection and modify specific fields of it with newer values in the same query. The command provided by MongoDB is findAndModify(). Please follow the details given below to understand the syntax of this command.
[Related Article: Aggregate MongoDB]
There are a lot of options that are available for usage on this method, as this can be used for more than one usage – insert if not exists, remove based on condition, update if exists and etc. Hence we will pick up one specific scenario to explain and the rest can be easily understood following the MongoDB documentation.
The query below tries to identify a record that matches to the given condition if there are no matches identified in the collection and when the upsert parameter is provided as true then a new document gets inserted into the collection and the same document is returned as the output to the command.
Syntax: db.SampleCollection.findAndModify({
query : {studentId : “1007”, studentName : “AkshayKumar”, studentGroup : “MPC”},
sort : { studentGrade : 1},
update : ($set : {studentGrade : “A+”}),
upsert : true,
new : true
})
RDBMS Syntax:
IF EXISTS
BEGIN
UPDATE SampleCollection set studentGrade = “A+”
WHERE studentId = “1007” AND studentName = “AkshayKumar” AND studentGroup = “MPC”
END
ELSE
BEGIN
INSERT INTO SampleCollection VALUES (“1007”, “AkshayKumar”, “MPC”, “A+”)
END
In this article, we have learned about various possible permutations and combinations of find() methods that we can apply to documents within collections to obtain the intended results. Though this article has in specific tried to add all the related details to this method alone, the method in itself is very vast and hence any details further to this have to be referred from the MongoDB official documentation.
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
MongoDB Training | Nov 23 to Dec 08 | View Details |
MongoDB Training | Nov 26 to Dec 11 | View Details |
MongoDB Training | Nov 30 to Dec 15 | View Details |
MongoDB Training | Dec 03 to Dec 18 | View Details |
Prasanthi is an expert writer in MongoDB, and has written for various reputable online and print publications. At present, she is working for MindMajix, and writes content not only on MongoDB, but also on Sharepoint, Uipath, and AWS.