Convert SQL ORDER BY to MongoDB sort() or $sort Stage
Learn how SQL ORDER BY with ASC and DESC directions maps to MongoDB sort() cursor method or $sort aggregation stage for result ordering.
Detailed Explanation
ORDER BY to sort() / $sort
SQL's ORDER BY sorts results by one or more columns. In MongoDB, this maps to the .sort() cursor method for find() queries or the $sort aggregation stage for pipelines.
Example SQL
SELECT * FROM products
ORDER BY price DESC, name ASC
Generated MongoDB Query (find)
db.products.find({}).sort({
price: -1,
name: 1
})
Generated MongoDB Query (aggregate)
db.products.aggregate([
{
$sort: {
price: -1,
name: 1
}
}
])
Direction Mapping
| SQL | MongoDB | Description |
|---|---|---|
ASC |
1 |
Ascending order (smallest to largest) |
DESC |
-1 |
Descending order (largest to smallest) |
| (default) | 1 |
SQL defaults to ASC; MongoDB requires explicit direction |
Multi-Field Sort
MongoDB respects the order of fields in the sort specification. In the example above, documents are first sorted by price descending, then by name ascending for documents with the same price. This matches SQL's behavior exactly.
Sort and Index Usage
For optimal performance, the sort fields and their directions should match an existing index. MongoDB can use an index to avoid an in-memory sort, which is subject to a 100 MB memory limit (configurable with allowDiskUse).
An index on { price: -1, name: 1 } would make the above query efficient. An index with reversed directions { price: 1, name: -1 } can also be used because MongoDB can traverse indexes in either direction.
Sort in Aggregation Pipeline
When using $sort in an aggregation pipeline, place it after $match and $group stages but before $limit and $skip for correct results. If $sort immediately precedes $limit, MongoDB optimizes this into a single operation that only tracks the top N results.
Use Case
Product listing pages with sortable columns, leaderboards, and any API endpoint supporting user-controlled sort parameters need ORDER BY conversion. Understanding the sort direction mapping and index implications ensures performant queries after migration.
Try It — SQL to MongoDB Query
Related Topics
Convert SQL LIMIT and OFFSET to MongoDB limit() and skip()
Migration
Convert a Simple SQL SELECT to MongoDB find()
Basic Queries
Convert SQL WHERE with Comparison Operators to MongoDB
Filtering
Convert SQL GROUP BY with COUNT to MongoDB $group with $sum
Aggregation
Convert SQL INNER JOIN to MongoDB $lookup with $unwind
Migration