In my previous tutorials I have used the find() method to query all the documents from a collection. In this tutorial, we will see the usage of find() method to query the documents from a collection based on the given criteria. Lets get started.
Querying all the documents in JSON format
Lets say we have a collection students
in a database named beginnersbookdb
. To get all the documents we use this command:
db.students.find()
However the output we get is not in any format and less-readable. To improve the readability, we can format the output in JSON format with this command:
db.students.find().forEach(printjson);
OR simply use pretty() – It does the same thing.
db.students.find().pretty()
As you can see in the screenshot below that the documents are in JSON format.
Query Document based on the criteria
Instead of fetching all the documents from collection, we can fetch selected documents based on a criteria.
Equality Criteria:
For example: I want to fetch the data of “Steve” from students collection. The command for this should be:
db.students.find({StudentName : "Steve"}).pretty()
This command returns the document matching the given criteria.
Greater Than Criteria:
Syntax:
db.collection_name.find({"field_name":{$gt:criteria_value}}).pretty()
For example: I would like to fetch the details of students having age > 32 then the query should be:
db.students.find({"age":{$gt:32}}).pretty()
I got two documents matching the criteria as shown in the screenshot below:
Less than Criteria:
Syntax:
db.collection_name.find({"field_name":{$lt:criteria_value}}).pretty()
Example: Find all the students having id less than 3000. The command for this criteria would be:
db.students.find({"StudentId":{$lt:3000}}).pretty()
Output:
> db.students.find({"StudentId":{$lt:3000}}).pretty() { "_id" : ObjectId("59bcecc7668dcce02aaa6fed"), "StudentId" : 1001, "StudentName" : "Steve", "age" : 30 } { "_id" : ObjectId("59bcecc7668dcce02aaa6fee"), "StudentId" : 1002, "StudentName" : "Negan", "age" : 42 }
Not Equals Criteria:
Syntax:
db.collection_name.find({"field_name":{$ne:criteria_value}}).pretty()
Example: Find all the students where id is not equal to 1002. The command for this criteria would be:
db.students.find({"StudentId":{$ne:1002}}).pretty()
Output:
> db.students.find({"StudentId":{$ne:1002}}).pretty() { "_id" : ObjectId("59bcecc7668dcce02aaa6fed"), "StudentId" : 1001, "StudentName" : "Steve", "age" : 30 } { "_id" : ObjectId("59bcecc7668dcce02aaa6fef"), "StudentId" : 3333, "StudentName" : "Rick", "age" : 35 }
Here are the other two criteria:
Greater than equals Criteria:
db.collection_name.find({"field_name":{$gte:criteria_value}}).pretty()
Less than equals Criteria:
db.collection_name.find({"field_name":{$lte:criteria_value}}).pretty()
The pretty() method that we have added at the end of all the commands is not mandatory. It is just used for formatting purposes.
Leave a Reply