MongoDB sort With Examples

MongoDB sort method sorts the document in either ascending or descending order as specified by the user in the input argument.

MongoDB sort

The syntax for MongoDB sort method is:

sort order can take the following values:

1: specifies that the field should be sorted in ascending order

-1: specifies that the field should be sorted in descending order

MongoDB sort example

Lets see an example for sorting the fields. Note that you can create the example data using MongoDB insert.

Sorts the car collection documents in descending order for the speed field.

As you can notice, this sorts the car collection documents in ascending order on the name field.

Above example sorts the car collection in descending order based on speed and then sorts on name in ascending order for the cars having same speed (65).

Limit the results of MongoDB sort operation

If the sort operation exceeds more than 32 megabytes, MongoDB returns an error. To get rid of this error, indexing can be used in conjunction with limit method. Limit results the number of documents to be returned within 32 megabytes.

For example;

This MongoDB sort operation limits the number of documents returned to 10 and ensures that it is within 32 megabytes limit.

Indexes can be created as shown below.

This ensures that the index is created for the car collection. We can also use Mongo shell createIndex() method for this.

Specifying Projection fields

When user specifies the fields to be projected and sorted the MongoDB engine sorts the resultant documents first.

For example;

This operation sorts the car by its speed in descending order first and then displays only id, name and speed fields in the resultant document.

Natural Ordering of MongoDB sort

The $natural parameter returns all the documents in the order they exist in the database. This ordering basically depicts the order in which the records are inserted except in the conditions where the documents relocate due to update or remove operations.

For example;

The documents are retrieved in the order in which they are inserted into the database.

MongoDB sort Java Program

In this section we will look into a java program to perform sort operation in ascending and descending orders.

Below is the MongoDB sort program for java driver versions 2.x.

Above program results in following output.

If you are using MongoDB java driver version 3.x, below code should work. It’s tested with version 3.5.0

That’s all for sorting documents in MongoDB, we will look into more of MongoDB features in coming posts.

By admin

Leave a Reply

%d bloggers like this: