Sorting, paging and projection
find() doesn't return an array: it returns a cursor, a pointer to the results that fetches documents in batches as you read them. You shape what the cursor returns with methods like sort, skip and limit.
Sorting
sort takes fields with 1 (ascending) or -1 (descending):
Sort by several fields: the second breaks ties in the first:
Without
sort, MongoDB returns documents in whatever order is convenient (often insertion order, but not guaranteed). If order matters, always sort.
Limit and skip: page by page
The order you chain the methods in doesn't matter: MongoDB always sorts, then skips, then limits.
Why skip gets slow, and the alternative
skip(100000) still makes the server walk past 100,000 documents. For large collections and infinite scroll, use range-based (keyset) pagination: remember the last value you showed, and ask for documents after it:
Including _id in the sort makes the order unique, so no document is skipped or repeated when prices are equal. With an index on { price: 1, _id: 1 }, every page is equally fast.
Projection in depth
You can't mix including and excluding in one projection (except for _id):
Projecting array elements
Computed fields
Projections can also compute new values with aggregation expressions:
Cursor methods
| Method | Does |
|---|---|
.toArray() |
All results as an array |
.forEach(fn) |
Run a function for each document |
.map(fn) |
Transform each document |
.hasNext() / .next() |
Iterate one at a time |
.limit(n), .skip(n), .sort(spec) |
Shape the results |
.explain() |
Show the query plan (next lesson) |
In application code (Node.js, Python…) you loop over cursors the same way. Drivers fetch documents in batches behind the scenes, so you can iterate over millions of documents without loading them all into memory.
Counting properly
| Method | Use |
|---|---|
countDocuments(filter) |
Accurate count of matching documents |
estimatedDocumentCount() |
Instant, approximate total from metadata (no filter) |
cursor.count() |
Deprecated: you'll see a warning |
Practice
- Show the 3 youngest customers (name and age only).
- Build page 3 of products sorted by name, 3 per page.
- Return each order's
status,total, and a computeditemCount(hint:{ $size: '$items' }).
1.In what order does MongoDB apply sort, skip and limit?
2.Why is keyset (range-based) pagination better than skip for deep pages?
3.What's wrong with the projection { name: 1, email: 0 }?