• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • Blog

The basic query operations cover the simple operations such as getting all of the documents in a MongoDB collection. Let’s look at an example of how we can accomplish this.

All of our code will be run in the MongoDB JavaScript command shell. Consider that we have a collection named ‘Employee’ in our MongoDB database and we execute the below command.

MongoDB Query Document using find()

Code Explanation:

  1. Employee is the collection name in the MongoDB database
  2. The find command is an in-built function which is used to retrieve the documents in the collection.

If the command is executed successfully, the following Output will be shown

Output:

MongoDB Query Document using find()

The output shows all the documents which are present in the collection.

We can also add criteria to our queries so that we can fetch documents based on certain conditions.

Let's look at a couple of examples of how we can accomplish this.

db.Employee.find({EmployeeName : "Smith"}).forEach(printjson);

Code Explanation:

  1. Here we want to find for an Employee whose name is "Smith" in the collection , hence we enter the filter criteria as EmployeeName : "Smith"

If the command is executed successfully, the following Output will be shown

Output:

MongoDB Query Document using find()

The output shows that only the document which contains "Smith" as the Employee Name is returned.

Now, let's take a look at another code example which makes use of the greater than search criteria. When this criteria is included, it actually searches those documents where the value of the field is greater than the specified value.

db.Employee.find({Employeeid : {$gt:2}}).forEach(printjson);

Code Explanation:

  1. Here we want to find for all Employee's whose id is greater than 2. The $gt is called a query selection operator, and what is just means is to use the greater than expression.

If the command is executed successfully, the following Output will be shown

Output:

MongoDB Query Document using find()

All of the documents wherein the Employee id is greater than 2 is returned.

 

YOU MIGHT LIKE: