MongoDB: Limiting Query Results

Subject: mongodb

MongoDB: Limiting Query Results

Limiting query results restricts the maximum number of documents a find() operation returns. It helps manage data transfer, improves performance, and supports pagination.

Why Limit Documents?

  • Pagination: Show only a subset of data per page (e.g., 10 or 20 items).
  • Performance Optimization: Reduces network load and processing time by fetching fewer documents.
  • Top N Queries: Easily retrieve top or bottom N documents based on criteria.
  • Resource Management: Prevents fetching huge datasets accidentally.

Core Concepts

  • Cursor: find() returns a cursor pointing to results; limit() applies to this cursor.
  • Order of Operations (logical):
    1. find() filters documents.
    2. sort() orders the results.
    3. skip() skips a number of documents.
    4. limit() restricts the count.
  • Numeric Argument: limit(n) takes a non-negative integer; 0 means no limit.

Node.js Examples

Assume a students collection in school_db with documents like:

1. Limiting Without Sorting (Arbitrary Order)

Retrieve the first 3 students found (order may vary):

2. Limiting with Sorting (Top N Results)

Retrieve top 2 students by highest GPA:

3. Combining limit() with skip() for Pagination

Retrieve 2nd page of students, 2 per page, sorted by name:

Key Takeaways

  • limit(n) restricts returned documents to n.
  • Combine limit() with sort() and skip() for effective pagination.
  • Always sort before limiting when order matters.
  • Limiting results improves performance and reduces data transfer.