Search⌘ K

Read Documents: Part 8

Explore how to effectively sort documents using ascending and descending order and maintain consistency using unique _id sorting. Learn to limit and offset query results with limit and skip methods to implement pagination. Understand the role of indexes in optimizing sort operations and how to work with cursors to access query results.

Sort

The sort method is used to sort documents.

Syntax:

Markdown
db.collection.find(<filter-query>, <projection>).sort({
field: value,
...
});

The field value should be 1 to sort the documents in ascending order, and -1 to sort the documents in descending order.

First, let’s insert some documents.

Markdown
db.tasks.insertMany([
{
name: 'Task 1',
priority: 1
},
{
name: 'Task 2',
priority: 2
}
]);

Next, we build a query to sort documents based on the priority.

db.tasks.find().sort({priority: -1});

This query returns the below output.

[
  {
    _id: ObjectId("60fc0026b7b1ef7b709ecf34"),
    name: 'Task 2',
    priority: 2
  },
  {
    _id: ObjectId("60fc0026b7b1ef7b709ecf33"),
    name: 'Task 1',
    priority: 1
  }
]

Sort consistency

We can return the documents in any order if we sort them by a field with duplicate values. This is because MongoDB doesn’t store ...