w3resource logo


mongodb sort results

MongoDB sort results from collection

rating has average rating 9 out of 10. Total 4 users rated.

<<PreviousNext>>

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

collection.find().sort( {column1:1or -1 [, column2:1 or -1] });

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"

mongodb query view data

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 :

>db.userdetails.find().sort({"education":1})

The SQL equivalent code is

Select * from userdetails order by education

Output of the command

mongodb sort by one column example1

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 :

>db.userdetails.find().sort({"education":-1})

The SQL equivalent code is

Select * from userdetails order by education desc;

Output of the command

Fetch results by sorting one column in descending order

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 :

>db.userdetails.find().sort({"education":1,"password":1})

The SQL equivalent code is

Select * from userdetails order by education,password desc;

Output of the command

Fetch results by sorting on more than one column

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.

photo credit: matsugoro via photopin cc

<<PreviousNext>>