Sorting documents using sort method or $sort aggregation pipeline in MongoDB

To sort documents inside a collection we have two choices: Sort method or using the $sort from the aggregation framework

Sort method in MongoDB

The sort method specifies the order in which the query return the matching results. the sort are applied to an operation that return a cursor like the find method. The sort method takes an object that takes as keys the name of the fields we want to sort the result with and as values either 1 (Ascending) or -1 (Descending).

Ascending Sort in MongoDB

db.articles.find().sort({name: 1});

RDBMS equivalent of ascending sort

SELECT * FROM articles order by name asc;

Descending Sort in MongoDB

db.articles.find().sort({name: -1});

RDBMS equivalent of descending sort

SELECT * FROM articles order by name desc;

Sort using multiple fields in MongoDB

db.articles.find().sort({name: -1, nbr: 1});

RDBMS equivalent of sort using multiple fields

SELECT * FROM articles order by name desc, nbr asc;

Sorting data with different Types in MongoDB

When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest:

  1. MinKey (internal type)
  2. Null
  3. Numbers (ints, longs, doubles, decimals)
  4. Symbol, String
  5. Object
  6. Array
  7. BinData
  8. ObjectId
  9. Boolean
  10. Date
  11. Timestamp
  12. Regular Expression
  13. MaxKey (internal type)

Example of comparing data that have different types

Documents insertion

db.t.insert([
	{"name": "44"},
	{"name": 55},
	{"name": "66"}
])

Ascending documents sorting

db.t.find().sort({name: 1})

Result

As mentioned before, the numbers has a lower priority than strings. So as we selected an ascending type of sort the number should come first before the strings and then come the natural order.

{ "_id" : ObjectId("5e382eb5cf4511c8241a4468"), "name" : 55 }
{ "_id" : ObjectId("5e382eb5cf4511c8241a4467"), "name" : "44" }
{ "_id" : ObjectId("5e382eb5cf4511c8241a4469"), "name" : "66" }

Sort documents using Aggregate $sort pipeline stage

The $sort aggregation pipeline stage takes the same parameters as the sort method.

Ascending documents order using $sort aggregation

db.p.aggregate([
{
	$sort: {
		name: 1
	}
}
])

Descending documents order using $sort aggregation

db.p.aggregate([
{
	$sort: {
		name: -1
	}
}
])