Sorting, Limiting and Pagination
find() returns a cursor. Before you read the first document you can chain methods onto it that tell the server how to shape the results:
| Method | Effect |
|---|---|
.sort({ field: 1 }) |
ascending order (-1 for descending) |
.limit(n) |
at most n documents |
.skip(n) |
skip the first n documents |
.count() |
how many match (deprecated: use db.coll.countDocuments(filter) instead) |
.toArray() |
read everything into an array |
.forEach(fn) / .map(fn) |
process documents one by one |
.hasNext() / .next() |
iterate manually |
Sorting
Without .sort(), MongoDB returns documents in whatever order is most convenient for it ("natural order"). That often looks like insertion order on a small collection, but it is not guaranteed. Always sort when order matters:
db.products.find({ category: 'tea' }).sort({ price: 1 }).forEach(p => print(p.price, p.name));
print('---');
db.products.find({ category: 'tea' }).sort({ price: -1 }).forEach(p => print(p.price, p.name));8 Chamomile Calm
9.5 Earl Grey
11 Masala Chai
12 Green Sencha
---
12 Green Sencha
11 Masala Chai
9.5 Earl Grey
8 Chamomile Calm
Sorting by several fields
The sort document is ordered: the second field only breaks ties in the first. Here customers are grouped by tier and sorted by name inside each tier:
db.customers.find({}, { name: 1, tier: 1 })
.sort({ tier: 1, name: 1 })
.forEach(c => print(c.tier.padEnd(9), c.name));gold Ada Lovelace
gold Barbara Liskov
gold Grace Hopper
silver Alan Turing
silver Edsger Dijkstra
silver Hedy Lamarr
silver Margaret Hamilton
standard Donald Knuth
standard Katherine Johnson
standard Linus Torvalds
standard Radia Perlman
standard Tim Berners-Lee
Tip: When the sort field can have ties (like
priceortier), add a unique field such as_idas the last sort key. That makes the order fully deterministic, which is essential for pagination.
Top N with limit
Sort plus limit gives you a "top N" list. The server only has to keep the best n documents, which is efficient:
const top = db.products.find({}, { _id: 0, name: 1, rating: 1 })
.sort({ rating: -1, _id: 1 })
.limit(3)
.toArray();
print(top);[
{ name: 'Ethiopia Yirgacheffe', rating: 4.9 },
{ name: 'Pour-Over Dripper', rating: 4.8 },
{ name: 'Dark Chocolate Bar', rating: 4.8 }
]
The order in which you chain sort, skip and limit doesn't matter: the server always sorts first, then skips, then limits.
Pagination with skip and limit
To show page p (starting at 1) with size items per page, skip (p - 1) * size documents:
function page(p, size) {
return db.products.find({}, { name: 1 })
.sort({ _id: 1 })
.skip((p - 1) * size)
.limit(size)
.toArray()
.map(doc => doc._id + ' ' + doc.name);
}
print('page 1:', page(1, 4));
print('page 3:', page(3, 4));
print('page 6:', page(6, 4));page 1: [
'1 Espresso Beans',
'2 House Blend',
'3 Ethiopia Yirgacheffe',
'4 Colombia Supremo'
]
page 3: [
'9 Masala Chai',
'10 Pour-Over Dripper',
'11 French Press',
'12 Burr Grinder'
]
page 6: []
A page beyond the end is simply empty.
Range-based pagination (faster)
skip(n) still walks over the skipped documents, so page 5,000 is slow. The alternative is to remember the last value of the previous page and ask for documents after it. With an index on the sort field this is fast for every page:
let lastId = 0;
for (let pageNo = 1; pageNo <= 3; pageNo++) {
const docs = db.orders.find({ _id: { $gt: lastId } }, { total: 1 })
.sort({ _id: 1 })
.limit(3)
.toArray();
print('page', pageNo, docs.map(o => o._id));
lastId = docs[docs.length - 1]._id;
}page 1 [ 1001, 1002, 1003 ]
page 2 [ 1004, 1005, 1006 ]
page 3 [ 1007, 1008, 1009 ]
Iterating a cursor by hand
A cursor fetches results in batches and can be consumed only once. hasNext() and next() let you step through it:
const cursor = db.orders.find({ status: 'shipped' }).sort({ _id: 1 });
while (cursor.hasNext()) {
const o = cursor.next();
print(o._id, o.date.toISOString().slice(0, 10), o.total);
}
print('more?', cursor.hasNext());1010 2026-04-09 49
1012 2026-04-18 48
1013 2026-04-25 28.5
more? false
Test yourself
Without .sort(), in which order does find() return documents?
- By
_id - By insertion time, guaranteed
- In an unspecified (natural) order
- Alphabetically
Which cursor shows page 3 with 10 items per page?
.skip(3).limit(10).skip(20).limit(10).skip(30).limit(10).limit(30)
Why add _id as a last sort key, as in sort({ price: 1, _id: 1 })?
- It is required by MongoDB
- It makes the order unique when prices tie
- It makes the query use less memory
- It sorts the _id descending