Sort and paginate
Sort the results and page through them without scanning too much.
Sort the results with sort and page through them. Without sort, TeselaDB returns documents in their key order, which need not be insertion order.
Requirements
- A connection with a user that has
readon the database. - An index on the field you sort by.
Sort
JavaScript
db.orders.find({ status: "paid" }).sort({ created: -1 }).limit(20);Paginate by a value
Ask for the next page from the last value you saw, without skipping documents with skip:
JavaScript
db.orders
.find({ status: "paid", created: { $lt: lastCreated } })
.sort({ created: -1 })
.limit(20);Check
Each page brings 20 documents and the next one starts where the previous one ended.
Common problems
skipwith a large number scans every skipped document on each page.- Without an index that covers the order, the sort can spill to disk or fail with
QueryExceededMemoryLimitNoDiskUseAllowed(292).