Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB0%

Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

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.
JavaScript
// 1. Delete a specific inactive user
const deleteRes = await db.collection('users').deleteOne({
_id: new ObjectId('64fa123456789abcdef01234')
});
console.log('Deleted Count:', deleteRes.deletedCount);
 
// 2. Bulk delete expired sessions older than 30 days
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const bulkDelete = await db.collection('sessions').deleteMany({
lastActive: { $lt: thirtyDaysAgo }
});
console.log('Purged expired sessions:', bulkDelete.deletedCount);

2. Cursor Operations: Sorting, Limit & Skip

Querying returns a cursor that allows chaining cursor modifiers before results are streamed over the network:

JavaScript
const page = 1;
const pageSize = 10;
 
const products = await db.collection('products')
.find({ inStock: true })
.sort({ price: 1, createdAt: -1 }) // 1 = Ascending, -1 = Descending
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();

3. The Problem with .skip() at Scale

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
// Fetch page 2: records after the last viewed document's _id
const lastSeenId = '64fa10000000000000000000';
 
const nextPageProducts = await db.collection('products')
.find({
inStock: true,
_id: { $gt: new ObjectId(lastSeenId) } // $O(1)$ fast indexed seek!
})
.sort({ _id: 1 })
.limit(10)
.toArray();

Keyset pagination executes with constant $O(1)$ index seek performance, regardless of whether you are viewing page 2 or page 2,000,000!


Interactive Quiz

Multiple Choice Questions

Question 1
In MongoDB sorting, what integer values represent Ascending and Descending order?
Question 2
Why does skip(100000) degrade performance severely in high-volume database queries?
Question 3
What is the performance advantage of Keyset (Cursor-based) pagination over Offset (Limit/Skip) pagination?
Question 4
What will collection.deleteMany({}) do if passed an empty filter object {}?
Question 5
Which method closes an open MongoDB Cursor manually when streaming results?

Next Lesson

Mongoose Connection Lifecycle, Schemas & Compiled Models

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext