MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
2.1Insert Operations: insertOne, insertMany & Write Concerns2.2Find Queries & Comparison Operators ($eq, $gt, $in, $nin)2.3Logical, Element & Array Query Operators ($and, $or, $exists, $all)2.4Update Operations: updateOne, updateMany & Field Modifiers ($set, $inc, $push)2.5Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB
HomeTutorialsMongoDB & MongooseDelete Operations, Cursors, Limit, Skip & Sorting in MongoDB
Mongoose Connection Lifecycle, Schemas & Compiled Models

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

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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

1const page = 1;
2const pageSize = 10;
3 
4const products = await db.collection('products')
5 .find({ inStock: true })
6 .sort({ price: 1, createdAt: -1 }) // 1 = Ascending, -1 = Descending
7 .skip((page - 1) * pageSize)
8 .limit(pageSize)
9 .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:

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

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.

Related Lessons

Previous LessonNext Lesson
Update Operations: updateOne, updateMany & Field Modifiers ($set, $inc, $push)Mongoose Connection Lifecycle, Schemas & Compiled Models

Practice Quiz

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

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext