Query MongoDB with Sorting and Limit

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

MongoDB Limit Query Results

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.

MongoDB Sort by Descending Order

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.

Ascending order is defined by value 1.

MongoDB Count

The concept of aggregation is to carry out a computation on the results which are returned in a query. For example, suppose you wanted to know what is the count of documents in a collection as per the query fired, then MongoDB provides the count() function.

Let’s look at an example of this.

db.Employee.count()

Code Explanation:

  1. The above code executes the count function.

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

Output:

MongoDB Count() & remove() function

The output clearly shows that 4 documents are there in the collection.

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
12 + 19 =