How to sort mongodb with pymongo
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Sorting in MongoDB with PyMongo is easy to write and easy to get subtly wrong. The API call itself is small, but correct sorting also depends on tie-breakers, index support, and whether the query is part of pagination, aggregation, or user-facing text ordering.
Basic sort() Syntax
PyMongo uses ASCENDING and DESCENDING constants for readability:
ASCENDING is equivalent to 1, and DESCENDING is equivalent to -1, so these are equivalent:
The constant form is usually easier to read.
Prepare Sample Data
Now you can sort by one field:
Multi-Field Sorting
If multiple documents share the same primary sort value, add more fields so the order is deterministic:
This says:
- sort highest
totalfirst - for equal totals, sort earliest
created_atfirst - for remaining ties, sort by
order_id
That last tie-breaker is often important for stable pagination.
Sorting with Filters
Sorting is commonly combined with a query filter:
This pattern is typical for timelines, order history, audit logs, or activity feeds.
Sorting in Aggregation Pipelines
You can also sort inside an aggregation pipeline:
Aggregation sorting is useful when the sort happens after filtering, grouping, projection, or computed fields.
Sorting a Single Best Match
When you only need one top-ranked document, find_one also accepts sort information:
This can be cleaner than calling find().sort(...).limit(1) when the intent is specifically "give me the best match."
Sorting Strings with Collation
If user-facing string order matters, collation can change sort behavior for case and locale rules:
Without collation, string ordering may not match user expectations, especially with mixed case or non-English alphabets.
Indexes Matter
Sorting large collections without a supporting index can be expensive. If a query pattern is common, build an index that matches the filter and sort order.
Then a query like:
has a much better chance of using the index efficiently.
For diagnosis, inspect the query plan:
Sorting and Pagination
The naive pagination pattern is:
This is fine for modest page counts, but large skip() values get slower because MongoDB still has to walk past the skipped documents. For deep pagination, range-based pagination using the last-seen sort key is usually better.
Common Pitfalls
The most common mistake is sorting without a tie-breaker. If many documents share the same sort value, the order can appear unstable across requests, which becomes especially painful in pagination.
Another issue is assuming that sort() alone guarantees good performance. On large collections, missing indexes can turn a simple-looking query into an expensive in-memory sort.
Finally, do not forget that collation affects string sorting semantics. If users expect case-insensitive or locale-aware ordering, plain binary sorting may look incorrect even though the query "worked."
Summary
- Use
sort(field, ASCENDING)orsort(field, DESCENDING)for basic ordering. - Add secondary sort keys for deterministic results.
- Align indexes with common filter-plus-sort query patterns.
- Use collation when text sorting must follow locale or case rules.
- Be careful with deep pagination, because large
skip()values do not scale well.
Related reading
- How to specify an Order or Sort using the C driver for MongoDB?
- How to specify packagesToScan in HibernateJpaAutoConfiguration?
- How to split the name string in mysql?
- How to start MySQL server from command line on Mac OS Lion?
- How to sort one list based on another?
- How to sort pandas dataframe by one column
- How to sort the letters in a string alphabetically in Python
- How to sort with lambda in Python

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.