Class FindCursor<T, TRaw>

Lazily iterates over the document results of a query.

Shouldn't be directly instantiated, but rather created via Collection.find.

Typed as FindCursor<T, TRaw> where T is the type of the mapped documents and TRaw is the type of the raw documents before any mapping. If no mapping function is provided, T and TRaw will be the same type. Mapping is done using the FindCursor.map method.

Example

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}

const collection = db.collection<Person>('people');
let cursor = collection.find().filter({ firstName: 'John' });

// Lazily iterate all documents matching the filter
for await (const doc of cursor) {
  console.log(doc);
}

// Rewind the cursor to be able to iterate again
cursor.rewind();

// Get all documents matching the filter as an array
const docs = await cursor.toArray();

cursor.rewind();

// Set options & map as needed
cursor: Cursor<string> = cursor
  .project<Omit<Person, 'age'>>({ firstName: 1, lastName: 1 })
  .map(doc => doc.firstName + ' ' + doc.lastName);

// Get next document from cursor
const doc = await cursor.next();

Type Parameters

Constructors

Properties

_buffer: TRaw[] = []
_filter: Filter<SomeDoc>
_httpClient: DataAPIHttpClient
_keyspace: string
_mapping?: ((doc) => T)

Type declaration

    • (doc): T
    • Parameters

      • doc: unknown

      Returns T

_nextPageState?: null | string
_options: FindOptions
_sortVector?: null | number[]
_state: CursorStatus = CursorStatus.Uninitialized

Accessors

  • get closed(): boolean
  • Whether the cursor is closed, whether it be manually, or because the cursor is exhausted.

    Returns boolean

    Whether or not the cursor is closed.

  • get keyspace(): string
  • The keyspace of the collection that's being iterated over.

    Returns string

    The keyspace of the collection that's being iterated over.

Methods

  • An async iterator that lazily iterates over all documents in the cursor.

    Note that there'll only be partial results if the cursor has been previously iterated over. You may use FindCursor.rewind to reset the cursor.

    If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return immediately.

    It will close the cursor when iteration is complete, even if it was broken early.

    Returns AsyncGenerator<T, void, void>

    Example

    for await (const doc of cursor) {
      console.log(doc);
    }
  • Returns the number of documents in the buffer. If the cursor is unused, it'll return 0.

    Returns number

    The number of documents in the buffer.

  • Returns a new, uninitialized cursor with the same filter and options set on this cursor. No state is shared between the two cursors; only the configuration.

    Like mongo, mapping functions are not cloned.

    Returns FindCursor<TRaw, TRaw>

    A behavioral clone of this cursor.

    Example

    const cursor = collection.find({ name: 'John' });
    
  • Sets the filter for the cursor, overwriting any previous filter. Note that this filter is weakly typed. Prefer to pass in a filter through the constructor instead, if strongly typed filters are desired.

    NB. This method acts on the original documents, before any mapping.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • filter: Filter<TRaw>

      A filter to select which documents to return.

    Returns this

    The cursor.

    See

    StrictFilter

  • Iterates over all documents in the cursor, calling the provided consumer for each document.

    If the consumer returns false, iteration will stop.

    Note that there'll only be partial results if the cursor has been previously iterated over. You may use FindCursor.rewind to reset the cursor.

    If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return immediately.

    It will close the cursor when iteration is complete, even if it was stopped early.

    Parameters

    • consumer: ((doc) => boolean) | ((doc) => void)

      The consumer to call for each document.

    Returns Promise<void>

    A promise that resolves when iteration is complete.

    Deprecated

    • Prefer the for await (const doc of cursor) { ... } syntax instead.
  • Retrieves the vector used to perform the vector search, if applicable.

    • If includeSortVector is not true, this will unconditionally return null. No find request will be made.

    • If sort: { $vector } was used, getSortVector() will simply regurgitate that same $vector.

    • If sort: { $vectorize } was used, getSortVector() will return the $vector that was created from the text.

    • If vector search is not used, getSortVector() will simply return null. A find request will still be made.

    If includeSortVector is true, and this function is called before any other cursor operation (such as .next() or .toArray()), it'll make an API request to fetch the sort vector, filling the cursor's buffer in the process.

    If the cursor has already been executed before this function has been called, no additional API request will be made to fetch the sort vector, as it has already been cached.

    But to reiterate, if includeSortVector is false, and this function is called, no API request is made, and the cursor's buffer is not populated; it simply returns null.

    Returns Promise<null | number[]>

    The sort vector, or null if none was used (or if includeSortVector !== true).

  • Tests if there is a next document in the cursor.

    If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return false.

    Returns Promise<boolean>

    Whether or not there is a next document.

  • Sets whether similarity scores should be included in the cursor's results.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • includeSimilarity: boolean = true

      Whether similarity scores should be included.

    Returns this

    The cursor.

  • Sets whether the sort vector should be fetched on the very first API call. Note that this is a requirement to use FindCursor.getSortVector—it'll unconditionally return null if this is not set to true.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • includeSortVector: boolean = true

      Whether the sort vector should be fetched on the first API call

    Returns this

    The cursor.

  • Sets the maximum number of documents to return.

    If limit == 0, there will be no limit on the number of documents returned.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • limit: number

      The limit for this cursor.

    Returns this

    The cursor.

  • Map all documents using the provided mapping function. Previous mapping functions will be composed with the new mapping function (new ∘ old).

    NB. Unlike Mongo, it is okay to map a cursor to null.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Type Parameters

    • R

    Parameters

    • mapping: ((doc) => R)

      The mapping function to apply to all documents.

        • (doc): R
        • Parameters

          • doc: T

          Returns R

    Returns FindCursor<R, TRaw>

    The cursor.

  • Fetches the next document from the cursor. Returns null if there are no more documents to fetch.

    If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return null.

    Returns Promise<null | T>

    The next document, or null if there are no more documents.

  • Sets the projection for the cursor, overwriting any previous projection.

    NB. This method acts on the original documents, before any mapping.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    To properly type this method, you should provide a type argument for T to specify the shape of the projected documents, with mapping applied.

    Type Parameters

    Parameters

    • projection: Projection

      Specifies which fields should be included/excluded in the returned documents.

    Returns FindCursor<R, RRaw>

    The cursor.

    Example

    const cursor = collection.find({ name: 'John' });

    // T is `any` because the type is not specified
    const rawProjected = cursor.project({ _id: 0, name: 1 });

    // T is { name: string }
    const projected = cursor.project<{ name: string }>({ _id: 0, name: 1 });

    // You can also chain instead of using intermediate variables
    const fluentlyProjected = collection
      .find({ name: 'John' })
      .project<{ name: string }>({ _id: 0, name: 1 });

    // It's important to keep mapping in mind
    const mapProjected = collection
      .find({ name: 'John' })
      .map(doc => doc.name);
      .project<string>({ _id: 0, name: 1 });

    See

    StrictProjection

  • Pulls up to max documents from the buffer, or all documents if max is not provided.

    Note that this actually consumes the buffer; it doesn't just peek at it.

    Parameters

    • Optional max: number

      The maximum number of documents to read from the buffer. If not provided, all documents will be read.

    Returns TRaw[]

    The documents read from the buffer.

  • Rewinds the cursor to its uninitialized state, clearing the buffer and any state. Any configuration set on the cursor will remain, but iteration will start from the beginning, sending new queries to the server, even if the resultant data was already fetched by this cursor.

    Returns void

  • Sets the number of documents to skip before returning.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • skip: number

      The skip for the cursor query.

    Returns this

    The cursor.

  • Sets the sort criteria for prioritizing documents. Note that this sort is weakly typed. Prefer to pass in a sort through the constructor instead, if strongly typed sorts are desired.

    NB. This method acts on the original documents, before any mapping.

    This method mutates the cursor, and the cursor MUST be uninitialized when calling this method.

    Parameters

    • sort: Sort

      The sort order to prioritize which documents are returned.

    Returns this

    The cursor.

    See

    StrictSort

  • Returns an array of all matching documents in the cursor. The user should ensure that there is enough memory to store all documents in the cursor.

    Note that there'll only be partial results if the cursor has been previously iterated over. You may use FindCursor.rewind to reset the cursor.

    If the cursor is uninitialized, it will be initialized. If the cursor is closed, this method will return an empty array.

    Returns Promise<T[]>

    An array of all documents in the cursor.