querydrill

Learn ›MongoDB fundamentals ›Sorting and pagination

Sorting results

find().sort()

1 is ascending, -1 is descending, and multiple keys are applied left to right. Worth knowing before you rely on it: MongoDB does not promise any particular order for documents whose sort keys are equal.

db.users.find().sort({
  age: -1
})
1   ascending
-1  descending

Multiple fields:

db.users.find().sort({
  age: -1,
  name: 1
})

Meaning:

Sort by age descending

If same age:
  sort by name ascending