MongoDB sort results from collection
has average rating
9
out of 10.
Total 4 users rated.
Description
In this page, we are going to discuss how to sort data for one or more specific columns in ascending or descending order.
Syntax
Parameters
| Arguments | Description |
|---|---|
| collection | Name of the collection. |
| column1, column2 | Name of the fields or columns. |
| 1 or -1 | indicates the order (1 for ascending and -1 for descending) |
Our database name is 'myinfo' and our collection name is 'userdetails'. Here, is the collection bellow.
Sample collection "userdetails"
Fetch results by sorting one column in ascending order
If we want to fetch the result by sorting on "education" column in ascending order, the following mongodb command can be used :
The SQL equivalent code is
Output of the command

The above output shows that, all the documents have appeared with ascending order on "education" column.
N.B. Here in the example, a "1" after "education" have introduce for sorting in descending order on "education" column.
Fetch results by sorting one column in descending order
If we want to fetch the result by sorting on "education" column in descending order, the following mongodb command can be used :
The SQL equivalent code is
Output of the command

The above output shows that, all the documents have appeared with ascending order on "education" column.
Fetch results by sorting on more than one column
If we want to fetch the result by sorting on "education" column in ascending order and "password" column in descending order whether two or more primary sort are same, the following mongodb command can be used :
The SQL equivalent code is
Output of the command

The above output shows that, all the documents have appeared with ascending order on "education" column and the "user_id" of last two documents are same. Then the "password" column for those rows have arranged in descending order.

