Python Tutorial
Python MongoDB - Sort
Order query results ascending or descending, on one field or many.
sort()
Chain .sort() onto a find cursor. Use 1 for ascending and -1 for descending.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
customers = client["mydatabase"]["customers"]
for doc in customers.find().sort("name"): # ascending (default)
print(doc["name"])
for doc in customers.find().sort("name", -1): # descending
print(doc["name"])Sort by Multiple Fields
Pass a list of (field, direction) tuples. Order matters: earlier fields take precedence.
from pymongo import ASCENDING, DESCENDING
cursor = customers.find().sort([
("age", ASCENDING),
("name", DESCENDING),
])
# youngest first; within the same age, names Z -> AASCENDING is just 1 and DESCENDING is -1. The named constants make intent clearer.
Sort With Limit: Top N
Combine sort and limit to get the top results efficiently.
top3 = client["shop"]["products"].find().sort("price", -1).limit(3)
for p in top3:
print(p["name"], p["price"]) # three most expensive productsSkip for Pagination
page, per_page = 2, 10
cursor = (customers.find()
.sort("name")
.skip((page - 1) * per_page)
.limit(per_page))
# rows 11-20 in name orderLarge skip values are slow — MongoDB still walks the skipped documents. For deep pagination, filter by the last seen value (range/keyset pagination) instead.
Sorting Needs Indexes at Scale
Sorting many documents without a supporting index forces an in-memory sort, which MongoDB caps at 100 MB. Create an index on the sort fields for large collections.
customers.create_index([("age", 1), ("name", -1)]) # supports the sort aboveBest Practices
- Use the
ASCENDING/DESCENDINGconstants for readability. - Index the fields you sort on — in the same order and direction.
- Pair
sortwithlimitfor efficient top-N queries. - Avoid huge
skipoffsets; prefer keyset pagination.
Try It Yourself
Exercise 1: Return the 3 newest documents (highest _id first).
Show solution
coll.find().sort("_id", -1).limit(3)Exercise 2: What do the values 1 and −1 mean in sort?
Show solution
1 = ascending, −1 = descending.
📘 Real-World Deep Dive
Knowing <strong>MongoDB Sort (MongoDB)</strong> well is what turns MongoDB from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MongoDB Sort that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from pymongo import MongoClient
db = MongoClient().shop
for u in db.users.find().sort("created_at", -1).limit(3):
print(u["email"])Expected Output
(see source)Common mistakes
- Inserting a
dictwith embeddeddatetimeworks, but naivedatetime(without UTC) leads to subtle comparison bugs. - Queries with type-mismatched values silently return no results — cast at the boundary or use
bsoncodecs. find()returns a cursor — calllist(cursor)only once you intend to materialise results.- Treating MongoDB Sort as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Project only the fields you need:
collection.find({}, {"name": 1}). - Use
bulk_writeinstead of looping over single inserts / updates — order-of-magnitude faster. - Create indexes:
collection.create_index([("field", pymongo.ASCENDING)]). - When working with MongoDB, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.