Read Documents: Part 8
Learn and practice the sort, limit, and offset operations while reading MongoDB documents.
We'll cover the following...
Sort
The sort
method is used to sort documents.
Syntax:
Press + to interact
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.
Press + to interact
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 ...