MongoDB Sort Documents
You can sort documents of a MongoDB query using sort() method.
MongoDB Sort Documents – To sort documents in a collection based on a field, use cursor.sort() method. Sort method accepts Field and Order pairs in a document as argument. Field indicates that sorting of documents will occur based on the field specified and Order specifies the sorting order.
In this tutorial, we shall learn to sort documents in a collection based on a field in ascending or descending order using cursor.sort() method with examples. We will also see how sorting works with multiple fields, how to sort by date or timestamp fields, and what to check when sorted results are not returned in the expected order.
MongoDB cursor.sort() method for ordered query results
The sort() method is applied to the cursor returned by find(). It does not change the documents stored in the collection. It only changes the order in which matching documents are returned by the query.
Common use cases for sorting MongoDB documents include showing newest records first, displaying users alphabetically, ranking products by price, or ordering records by a status and then by a date.
Syntax of sort() method
The syntax of sort() method is
cursor.sort({field:order, field:order [, field:order] })
field [String] : any field name
order [Number] : 1 or -1 is allowed
| Order | Description |
| 1 | Ascending (Increasing) Order |
| -1 | Descending (Decreasing) Order |
Document to the sort() method is mandatory. But field:order pairs are optional. Which means, at the least sort() method expects an empty document.
Note : db.collection.find() returns cursor to the records. And sort() method can be applied on this cursor to sort the documents in increasing or decreasing order :
db.collection.find().sort({FIELD:ORDER})
For the official reference, see MongoDB documentation for cursor.sort(). If you are using MongoDB Compass, the MongoDB documentation also explains how to sort query results in Compass.
Example 1 – Sort Documents
In this example, we will sort the documents in resulting query, in ascending order, based on the field "age".
> db.customers.find().sort({"age":1});
{ "_id" : ObjectId("59edffea5f82df4555f2bfac"), "name" : "Midhuna", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfaf"), "name" : "Manju", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfad"), "name" : "Akhil", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb0"), "name" : "Bharat", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb1"), "name" : "Arya", "age" : 25 }
Documents are sorted in ascending order based on the field specified.
When two or more documents have the same value for the sorted field, MongoDB may return those matching values in any order unless you add another field to the sort document. To make the order predictable, add a second field such as name or _id.
Sorting MongoDB documents in descending order
Use -1 to sort a field in descending order. This is commonly used for showing higher values first, such as latest dates, highest prices, or largest scores.
db.customers.find().sort({ "age": -1 })
The above query returns customers with the highest age values first. For ascending order, use 1; for descending order, use -1.
Example 2 – sort() Default Behaviour
In this example, we will call sort() method on a query, with no argument specified. By default the documents are ordered by _id in ascending order.
> db.customers.find().sort({});
{ "_id" : ObjectId("59edffea5f82df4555f2bfac"), "name" : "Midhuna", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfad"), "name" : "Akhil", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfaf"), "name" : "Manju", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb0"), "name" : "Bharat", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb1"), "name" : "Arya", "age" : 25 }
The documents are sorted in the ascending order of _id.
In practical queries, it is better to provide the field names explicitly. If you need the newest documents first and the collection uses ObjectId values generated in insertion order, you can sort by _id descending. If your documents contain a real date field such as createdAt, sort by that date field instead.
db.customers.find().sort({ "_id": -1 })
Example 3 – Sort with Multiple Fields
In this example, we will sort the documents based on multiple fields and their specified respective order. We have given two fields “age” and “name” and specified their respective orders to sort() method.
> db.customers.find().sort({"age":1,"name":1});
{ "_id" : ObjectId("59edffea5f82df4555f2bfaf"), "name" : "Manju", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfac"), "name" : "Midhuna", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfad"), "name" : "Akhil", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb0"), "name" : "Bharat", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb1"), "name" : "Arya", "age" : 25 }
> db.customers.find().sort({"age":1,"name":-1});
{ "_id" : ObjectId("59edffea5f82df4555f2bfac"), "name" : "Midhuna", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfaf"), "name" : "Manju", "age" : 23 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb0"), "name" : "Bharat", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfad"), "name" : "Akhil", "age" : 24 }
{ "_id" : ObjectId("59edffea5f82df4555f2bfb1"), "name" : "Arya", "age" : 25 }
The command db.customers.find().sort({“age”:1,”name”:1}); first sorted the documents based on age in ascending order, then the documents with same age value are sorted in ascending order based on “name”.
The command db.customers.find().sort({“age”:1,”name”:-1}); first sorted the documents based on age in ascending order, then the documents with same age value are sorted in descending order based on “name”.
MongoDB applies the sort fields from left to right. In {"age":1,"name":-1}, age is the primary sort field and name is used only when two documents have the same age value.
Sorting MongoDB documents by date or timestamp field
To show recent records first, sort by a date or timestamp field in descending order. This is better than depending on natural collection order because natural order is not a reliable application-level sort order.
db.orders.find().sort({ "createdAt": -1 })
To show the oldest records first, use ascending order.
db.orders.find().sort({ "createdAt": 1 })
Make sure the field is stored as a proper MongoDB date value when you want date ordering. If dates are stored as strings, MongoDB sorts them as strings, which can produce unexpected results unless the string format is consistently sortable.
Using sort() with limit() in MongoDB queries
sort() is often used with limit() when you need only the top few or latest few documents. For example, the following query returns the five newest orders by createdAt.
db.orders.find().sort({ "createdAt": -1 }).limit(5)
You can also combine a filter with sorting. The next query returns active customers ordered alphabetically by name.
db.customers.find({ "status": "active" }).sort({ "name": 1 })
MongoDB sort() and index considerations
Sorting can be efficient when MongoDB can use an index that matches the query and sort pattern. Without a useful index, MongoDB may need to sort the matching documents in memory. For frequently used sorted queries, create an index that supports the fields used in the filter and sort.
For example, if the application often queries active customers and sorts them by name, an index on status and name can help.
db.customers.createIndex({ "status": 1, "name": 1 })
For a multi-field sort, the order of fields in the index matters. Create indexes based on actual query patterns instead of adding indexes for every possible sort field.
MongoDB aggregation $sort stage
When you use an aggregation pipeline, sort documents with the $sort stage instead of the cursor sort() method. The syntax is similar, but it is written as a pipeline stage.
db.customers.aggregate([
{ $match: { status: "active" } },
{ $sort: { age: 1, name: 1 } }
])
Use cursor.sort() with normal find() queries. Use $sort inside aggregation pipelines when the sorted result depends on pipeline stages such as $match, $project, $group, or calculated fields. For reference, see the MongoDB documentation for the $sort aggregation stage.
Common mistakes while sorting MongoDB documents
- Using the wrong order value: MongoDB sort order should be
1for ascending and-1for descending. - Expecting a stable order for equal values: Add another sort field such as
_idwhen many documents have the same value. - Sorting date strings instead of date values: Store dates as MongoDB date values when date ordering is required.
- Forgetting indexes on large sorted queries: Repeated sorted queries may need supporting indexes.
- Using cursor sort syntax inside aggregation: Use
$sortas an aggregation stage when working with pipelines.
MongoDB sort documents FAQ
How do I sort documents in MongoDB?
Use db.collection.find().sort({ field: 1 }) for ascending order and db.collection.find().sort({ field: -1 }) for descending order.
How do I sort MongoDB documents by newest first?
Sort a date or timestamp field in descending order, for example db.orders.find().sort({ createdAt: -1 }). If you do not have a date field and ObjectId values are generated normally, sorting by _id: -1 can often show newer inserted documents first, but an explicit date field is clearer.
Can MongoDB sort by more than one field?
Yes. Pass multiple fields to sort(), such as { age: 1, name: -1 }. MongoDB sorts by the first field, and then uses the next field when values are equal.
Does MongoDB sort() change documents in the collection?
No. The sort() method only changes the order of query results. It does not update, rewrite, or reorder the documents stored in the collection.
What is the difference between sort() and $sort in MongoDB?
sort() is used with a cursor returned by find(). $sort is an aggregation pipeline stage used inside aggregate().
MongoDB sort documents tutorial QA checklist
- Explains that
cursor.sort()orders query results and does not modify stored documents. - Shows ascending and descending sort order using
1and-1. - Includes single-field and multi-field sorting examples for MongoDB documents.
- Mentions date or timestamp sorting for newest-first and oldest-first queries.
- Clarifies when to use
sort()withfind()and when to use$sortin aggregation. - Notes index considerations for frequently used sorted queries.
Conclusion
In this MongoDB Tutorial – MongoDB Sort Documents, we have learnt to sort documents of a collection based on fields in ascending or descending order. We also covered multi-field sorting, date-based sorting, sorting with limit, index considerations, and the difference between cursor sort() and aggregation $sort.
TutorialKart.com