Skip to main content
MongoDB
CHAPTER 11 Beginner

MongoDB Sort & Limit | Pagination with skip()

Updated: May 16, 2026
15 min read

# CHAPTER 11

Sorting, Limiting, and Pagination

1. Introduction

If you search an E-Commerce site for "Laptops", the database might find 5,000 matches. If the database sends all 5,000 laptops to your phone at once, your phone will crash. To solve this, applications present data in chunks—"Page 1 of 500"—and sort them by "Highest Price" or "Newest". In this chapter, we will learn how to chain cursor methods onto our find() queries to Sort, Limit, and Paginate our data exactly like a modern web application.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Arrange results alphabetically or numerically using sort().
  • Restrict the total number of returned documents using limit().
  • Bypass documents using skip().
  • Combine all three methods to architect a standard Pagination system.

3. Arranging Data with sort()

When you run a find() query, MongoDB returns the data in roughly the order it was inserted on the hard drive. To enforce a specific order, you append the .sort() method to your query.

Inside sort(), you pass an object.

  • 1 = Ascending (A-Z, 0-9, Oldest to Newest)
  • -1 = Descending (Z-A, 9-0, Newest to Oldest)

javascript
12345678
// Find all users and sort them by age, youngest to oldest (Ascending)
db.users.find().sort({ age: 1 })

// Sort products by Price, Highest to Lowest (Descending)
db.products.find().sort({ price: -1 })

// Multi-level sorting: Sort by Last Name (A-Z), and if they have the same name, sort by Age (Oldest to Youngest)
db.users.find().sort({ last_name: 1, age: -1 })

4. Restricting Data with limit()

To prevent crashing your frontend application, you should *always* limit the maximum number of documents returned. The .limit() method cuts the result set off at a specific number.
javascript
12
// Give me ALL users, but only send the first 5 results over the network!
db.users.find().limit(5)

5. Combining Sort and Limit (Top 10 Lists)

By chaining methods together, you can create powerful leaderboards instantly!
javascript
1234
// Get the Top 3 highest-scoring players!
// 1. Sort by score descending (Highest first)
// 2. Limit to exactly 3 results
db.players.find().sort({ score: -1 }).limit(3)

6. Bypassing Data with skip()

The .skip() method tells MongoDB to literally step over a certain number of documents before it starts collecting results to send back. By itself, it is rarely used, but when combined with limit(), it unlocks Pagination.
javascript
12
// Step over the first 10 users, and return the 11th user onwards.
db.users.find().skip(10)

7. Mini Project: Architecting a Pagination System

Let's build the backend logic for an E-Commerce search results page. We want to display 10 products per page, sorted by Highest Price.
javascript
1234567891011
// PAGE 1 (Items 1-10)
// Skip 0, grab the first 10
db.products.find().sort({ price: -1 }).skip(0).limit(10)

// PAGE 2 (Items 11-20)
// Skip the 10 we already saw on Page 1, grab the next 10!
db.products.find().sort({ price: -1 }).skip(10).limit(10)

// PAGE 3 (Items 21-30)
// Skip the 20 we saw on Pages 1 & 2, grab the next 10!
db.products.find().sort({ price: -1 }).skip(20).limit(10)

*(In a Node.js backend, the math is always: skip = (pagenumber - 1) * itemsper_page).*

8. Common Mistakes

  • Method Chaining Order: You might write db.users.find().limit(5).sort({age: 1}). You might think this grabs 5 random users and then sorts those 5. It does not! MongoDB is incredibly smart. Behind the scenes, the engine *always* applies the sort() first, then the skip(), and finally the limit(), regardless of what order you type them in the shell.
  • Large Skips are Slow: If a user clicks "Page 10,000", skip(100000) forces MongoDB to physically scan and count 100,000 documents just to bypass them. This is devastating to performance. (Modern apps use "Cursor-based pagination" for massive datasets, which we will discuss later).

9. Best Practices

  • Always Sort by an Indexed Field: If you run .sort({ price: -1 }) on a collection with 5 million products, MongoDB has to load 5 million items into RAM to calculate the sorting order. This will crash the server. You MUST create an Index on the price field, which maintains a pre-sorted B-Tree on the hard drive!

10. Exercises

  1. 1. What value (1 or -1) do you pass into sort() to arrange Dates from Newest to Oldest?
  1. 2. If you want to display 20 items per page, how many items do you .skip() to display Page 4?

11. MongoDB Challenges

Write a single chained query to find all "Action" movies, sort them by rating from highest to lowest, and return only the top 5 results.
javascript
1
db.movies.find({ genre: "Action" }).sort({ rating: -1 }).limit(5)

12. MCQ Quiz with Answers

Question 1

In a MongoDB sort() method, what do the integer values 1 and -1 represent?

Question 2

When building a web pagination system (e.g., displaying "Page 2" of search results), which two cursor methods MUST be combined?

13. Interview Questions

  • Q: Explain how you would implement a standard offset pagination system for a REST API using MongoDB's skip() and limit() methods.
  • Q: A developer complains that querying "Page 500" of an application is taking 8 seconds to load, whereas "Page 1" loads in 50 milliseconds. Explain the mechanical reason why massive .skip() values destroy database performance.

14. FAQs

Q: Can I sort text alphabetically, ignoring capital letters? A: Yes. By default, MongoDB sorts case-sensitively (Z comes before a). To do case-insensitive sorting, you must define a "Collation" option on your query that specifies linguistic rules (e.g., { locale: "en", strength: 2 }).

15. Summary

By mastering cursor methods, you have taken control of how data flows from the database to the client. You can architect Top 10 leaderboards using sort and limit, and you can build the backend foundations for modern, paginated web applications utilizing dynamic skip math.

16. Next Chapter Recommendation

Our queries are perfect, but as our database approaches 10 million rows, finding and sorting data is becoming dangerously slow. In Chapter 12: MongoDB Indexing and Performance, we will unlock the ultimate secret of database engineering: B-Tree Indexes.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·