Sorting and Limiting Records in MongoDB
We can sort the documents in the MongoDB in two ways
- Using sort() method
- Using $sort operator
Sort ():-
Which will sorts all input documents
and returns them to the pipeline in sorted order.
Syntax:-
cursor.sort(sort)
Parameter | Type | Description |
---|---|---|
sort | document | A document that defines the sort order of the result set. |
Ascending/Descending Sort
Specify in the
sort parameter the field or fields to sort by and a value of 1
or -1 to specify an ascending(1) or descending(-1) sort
respectively.
Example:-
Display ‘users’
collection based on age in descending order
>db.users.find().sort({Age:-1})
Output:-
{ "_id" : ObjectId("5774c4b4fc520de27ab8745e"), "userid" :
null, "Age" : 44}
{ "_id" :
ObjectId("5774c4b4fc520de27ab8745d"), "userid" : "Andrew", "Age"
: 25}
{ "_id" : ObjectId("5774c4b4fc520de27ab8745c"),
"userid" : "Alex", }
$sort :-
It will
operate in the same way as sort() but this operator can be
applied with aggregate() whereas sort() will works only with
cursor(return result of find() methods)
In the aggregation
section it will be explained clearly.