> This page location: /docs.md > /docs/drivers.md > /docs/languages/javascript.md > /docs/drivers/node/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Access Data From a Cursor

## Overview

Read operations that return multiple documents do not immediately return all values matching the query. Because a query can potentially match very large sets of documents, these operations return an object called a cursor, which references documents identified by the query. A cursor fetches documents in batches to reduce both memory consumption and network bandwidth usage. Cursors are highly configurable and offer multiple interaction paradigms for different use cases.

The following functions directly return cursors:

- `Collection.find()`

- `Collection.aggregate()`

- `Collection.listIndexes()`

- `Collection.listSearchIndexes()`

- `Db.aggregate()`

- `Db.listCollections()`

Other methods such as [Collection.findOne()](https://www.mongodb.com/docs/drivers/node/current/crud/query/retrieve.md#std-label-node-usage-findone) and [Collection.watch()](https://www.mongodb.com/docs/drivers/node/current/monitoring-and-logging/change-streams.md) use cursors internally, and return the results of the operations instead of a cursor.

## Cursor Paradigms

You can use several different **cursor paradigms** to access data. Most cursor paradigms allow you to access query results one document at a time, abstracting away network and caching logic. However, since use cases differ, other paradigms offer different access patterns, like pulling all matching documents into a collection in process memory.

**Warning:**

Do not combine different cursor paradigms on a single cursor. Operations such as `hasNext()` and `toArray()` each predictably modify the original cursor. If you mix these calls on a single cursor, you may receive unexpected results.

**Warning:**

Because asynchronous calls directly modify the cursor, executing asynchronous calls on a single cursor simultaneously can also cause undefined behavior. Always wait for the previous asynchronous operation to complete before running another.

**Note:**

When you reach the last result through iteration or through an at-once fetch, the cursor is  **exhausted**,  which means it ceases to respond to methods that access the results.

### Asynchronous Iteration

Cursors implement the [AsyncIterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) interface, which allows you to use cursors in `for await...of` loops:

```javascript
  const cursor = myColl.find({});
  console.log("async");
  for await (const doc of cursor) {
    console.log(doc);
  }
```

### Manual Iteration

You can use the [hasNext()](https://mongodb.github.io/node-mongodb-native/7.8/classes/FindCursor.html#hasNext) method to check if a cursor can retrieve more data, and then use the [next()](https://mongodb.github.io/node-mongodb-native/7.8/classes/FindCursor.html#next) method to retrieve the subsequent element of the cursor:

```javascript
  const cursor = myColl.find({});

  while (await cursor.hasNext()) {
    console.log(await cursor.next());
  }
```

### Return an Array of All Documents

For use cases that require all documents matched by a query to be held in memory at the same time, use the [toArray()](https://mongodb.github.io/node-mongodb-native/7.8/classes/FindCursor.html#toArray) method. Note that large numbers of matched documents can cause performance issues or failures if the operation exceeds memory constraints. Consider using the `for await...of` syntax to iterate through results rather than returning all documents at once.

```javascript
  const cursor = myColl.find({});
  const allValues = await cursor.toArray();
```

### Stream API

Cursors expose the `stream()` method to convert them to Node Readable Streams. These streams operate in **Object
Mode**, which passes JavaScript objects rather than Buffers or Strings through the pipeline.

```javascript
  const cursor = myColl.find({});
  cursor.stream().on("data", doc => console.log(doc));
```

### Event API

As Readable Streams, cursors also support the Event API's `close`, `data`, `end`, and `readable` events:

```javascript
  const cursor = myColl.find({});
  // the "data" event is fired once per document
  cursor.on("data", data => console.log(data));
```

## Cursor Utility Methods

### Rewind

To reset a cursor to its initial position in the set of returned documents, use [rewind().](https://mongodb.github.io/node-mongodb-native/7.8/classes/FindCursor.html#rewind)

```javascript
  const cursor = myColl.find({});
  const firstResult = await cursor.toArray();
  console.log("First count: " + firstResult.length);
  await cursor.rewind();
  const secondResult = await cursor.toArray();
  console.log("Second count: " + secondResult.length);
```

### Close

Cursors consume memory and network resources both in the client application and in the connected instance of MongoDB. Use [close()](https://mongodb.github.io/node-mongodb-native/7.8/classes/FindCursor.html#close) to free up a cursor's resources in both the client application and the MongoDB Server, as shown in the following example:

```javascript
  await cursor.close();
```

We recommend manually closing any non-exhausted cursors that your application no longer uses to prevent resource leaks.

**Tip: Explicit Resource Management**

The Node.js driver natively supports explicit resource management for `MongoClient`, `ClientSession`, `ChangeStreams`, and cursors. This feature is experimental and subject to change. To learn how to use explicit resource management, see the [v6.9 Release Notes.](https://github.com/mongodb/node-mongodb-native/releases/tag/v6.9.0)

### Abort

You can cancel cursor operations by using an [abort signal](https://mongodb.github.io/node-mongodb-native/7.8/types/Abortable.html).  This can help you manage your resources by releasing memory and network resources used by the cursor if they're no longer needed.

**Note:**

This feature is experimental. Aborting a signal closes a connection, which might cause unnecessary connection reestablishment.

You can pass the `signal` command to the following methods:

- `collection.find()`

- `collection.findOne()`

- `collection.aggregate()`

- `collection.countDocuments()`

- `db.listCollections()`

- `db.command()`

To use an abort signal, create an `AbortController` instance and extract the `signal` from the controller. In this code example, the process listens for a `SIGINT` (`Ctrl+C`) to trigger the `abort()` method. You can pass the `signal` option to the `find()` method to abort the cursor operation if the signal triggers, as shown in the following example:

```javascript
  const controller = new AbortController();
  const { signal } = controller;

  process.on('SIGINT', () => controller.abort(new Error('^C pressed')));

  try {
    const cursor = myColl.find({}, { signal });
    for await (const doc of cursor) {
      console.log(doc);
    }
  } catch (error) {
    if (error === signal.reason) {
      console.error('Operation aborted:', error);
    } else {
      console.error('Unexpected error:', error);
    }
  }
```
