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

Mongo DB provides query modifiers such as the 'limit' and 'Orders' clause to provide more flexibility when executing queries. We will take a look at the following query modifiers

  1. Limits

This modifier is used to limit the number of documents which are returned in the result set for a query. The following example shows how this can be done.

db.Employee.find().limit(2).forEach(printjson);

Code Explanation:

  1. The above code takes the find function which returns all of the documents in the collection but then uses the limit clause to limit the number of documents being returned to just 2.

Output:

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

MongoDB Query Modifications using limit(), sort()

The output clearly shows that since there is a limit modifier, so at most just 2 records are returned as part of the result set based on the ObjectId in ascending order.

  1. Orders

One can specify the order of documents to be returned based on ascending or descending order of any key in the collection. The following example shows how this can be done.

db.Employee.find().sort({Employeeid:-1}).forEach(printjson)

Code Explanation:

  1. The above code takes the sort function which returns all of the documents in the collection but then uses the modifier to change the order in which the records are returned. Here the -1 indicates that we want to return the documents based on the descending order of Employee id.

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

Output:

MongoDB Query Modifications using limit(), sort()

The output clearly shows the documents being returned in descending order of the Employeeid.

 

YOU MIGHT LIKE: