Sorting and Limiting Records in MongoDB

We can sort the documents in the MongoDB in two ways

  1. Using sort() method
  2. 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.

Display ‘users’ collection based on age in descending order


{ "_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.

Copyright © 2018-2020 TutorialToUs. All rights reserved.