Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB
Efficiently managing query volume and deleting obsolete data is vital for scalable systems. In this tutorial, we cover deleteOne(), deleteMany(), and the mechanics of Cursors, including sorting and pagination using Limit/Skip versus Cursor-Based (Keyset) Pagination.
1. Delete Operations
deleteOne(filter): Deletes the first document matching the filter.
deleteMany(filter): Deletes all documents matching the filter.
While skip((page - 1) * limit) is simple, it has an $O(N)$ performance drawback. To skip 1,000,000 documents, MongoDB must traverse and count through 1,000,000 index entries before returning the 10 requested items.
The Solution: Keyset (Cursor-Based) Pagination
Instead of skip(), query using an indexed field (such as _id or createdAt) greater or less than the last document of the previous page:
JavaScript
1// Fetch page 2: records after the last viewed document's _id