Skip to main content

Command Palette

Search for a command to run...

Cursor in MongoDB

Published
2 min read
Cursor in MongoDB

When we run a query in MongoDB, it may look like all results are returned at once.

But behind the scenes, MongoDB uses something called a cursor to fetch documents efficiently.

What is a MongoDB Cursor?

A cursor is a pointer to the result set of a query.

When you run a find() query, MongoDB does not immediately return all matching documents.
Instead, it returns a cursor that:

  • Points to the matching documents

  • Fetches documents in batches

  • Allows iteration over the result set

Why Does MongoDB Use Cursors?

Imagine a collection with millions of documents.

If MongoDB returned everything at once:

  • High memory usage ❌

  • Network overload ❌

  • Slow performance ❌

Cursors solve this by:

  • Stream large result sets efficiently

  • Avoid loading all documents into memory

  • Maintain consistent performance even for large collections

How Cursor Works Internally

  1. Client sends a find() query

  2. MongoDB:

    • Finds matching documents

    • Returns the first batch (default ~101 docs)

    • Creates a cursor ID

  3. Once the first batch is fully consumed, the MongoDB driver automatically sends a getMore command to the server.

  4. MongoDB sends the next batch

  5. This cycle continues until:

    All documents are read, or

    The cursor is closed or times out

MongoDB Operations That Return Cursors

A few operations that send a response as a cursor are

  • find()

  • aggregate()

  • listCollections()

  • listIndexes()

Code:

Without Cursor

const data = await db.collection("users")
  .find({ age: { $gt: 20 } })
  .toArray();

data.forEach(user => {
  console.log(user);
});

→ Loads everything into memory first.

With Cursor

const cursor = db.collection("users")
  .find({ age: { $gt: 20 } });
for await (const doc of cursor) {
   console.log(doc)
}

→ Streams documents in batches, no memory blow-up.