MongoDB::Cursor - A cursor/iterator for Mongo query results


version v0.704.1.0


    while (my $object = $cursor->next) {

    my @objects = $cursor->all;


Cursors are cloned in threads, but not reset. Iterating the same cursor from multiple threads will give unpredictable results. Only iterate from a single thread.


MongoDB::Cursor - A cursor/iterator for Mongo query results


Core documentation on cursors:



    $MongoDB::Cursor::slave_okay = 1;

Whether it is okay to run queries on the slave. Defaults to 0.


Deprecated, use MongoDB::Connection::query_timeout instead.

How many milliseconds to wait for a response from the server. Set to 30000 (30 seconds) by default. -1 waits forever (or until TCP times out, which is usually a long time).

This value is overridden by MongoDB::Connection::query_timeout and never used.



If this cursor has queried the database yet. Methods modifying the query will complain if they are called after the database is queried.



Ordinarily, a cursor "dies" on the database server after a certain length of time (approximately 10 minutes), to prevent inactive cursors from hogging resources. This option sets that a cursor should not die until all of its results have been fetched or it goes out of scope in Perl.

Boolean value, defaults to 0.

immortal is not equivalent to setting a client-side timeout. If you are getting client-side timeouts (e.g., "recv timed out"), set query_timeout on your connection.

    # wait forever for a query to return results

See "query_timeout" in MongoDB::Connection.


If a shard is down, mongos will return an error when it tries to query that shard. If this is set, mongos will just skip that shard, instead.

Boolean value, defaults to 0.



If a query can be done on a slave database server.

Boolean value, defaults to 0.


fields (\%f)

    $coll->insert({name => "Fred", age => 20});
    my $cursor = $coll->query->fields({ name => 1 });
    my $obj = $cursor->next;
    $obj->{name}; "Fred"
    $obj->{age}; # undef

Selects which fields are returned. The default is all fields. _id is always returned.

sort ($order)

    # sort by name, descending
    my $sort = {"name" => -1};
    $cursor = $coll->query->sort($sort);

Adds a sort to the query. Argument is either a hash reference or a Tie::IxHash. Returns this cursor for chaining operations.

limit ($num)

    $per_page = 20;
    $cursor = $coll->query->limit($per_page);

Returns a maximum of N results. Returns this cursor for chaining operations.

max_time_ms( $millis )

    $cursor = $coll->query->max_time_ms( 500 );

Causes the server to abort the operation if the specified time in milliseconds is exceeded.

tailable ($bool)


If a cursor should be tailable. Tailable cursors can only be used on capped collections and are similar to the tail -f command: they never die and keep returning new results as more is added to a collection.

They are often used for getting log messages.

Boolean value, defaults to 0.

Returns this cursor for chaining operations.

skip ($num)

    $page_num = 7;
    $per_page = 100;
    $cursor = $coll->query->limit($per_page)->skip($page_num * $per_page);

Skips the first N results. Returns this cursor for chaining operations.

See also core documentation on limit:


    my $cursor = $coll->query->snapshot;

Uses snapshot mode for the query. Snapshot mode assures no duplicates are returned, or objects missed, which were present at both the start and end of the query's execution (if an object is new during the query, or deleted during the query, it may or may not be returned, even with snapshot mode). Note that short query responses (less than 1MB) are always effectively snapshotted. Currently, snapshot mode may not be used with sorting or explicit hints.


    my $cursor = $coll->query->hint({'x' => 1});

Force Mongo to use a specific index for a query.


    my $explanation = $cursor->explain;

This will tell you the type of cursor used, the number of records the DB had to examine as part of this query, the number of records returned by the query, and the time in milliseconds the query took to execute. Requires boolean package.

explain resets the cursor, so calling next or has_next after an explain will requery the database.

See also core documentation on explain:


    my $num = $cursor->count;
    my $num = $cursor->skip(20)->count(1);

Returns the number of document this query will return. Optionally takes a boolean parameter, indicating that the cursor's limit and skip fields should be used in calculating the count.


Resets the cursor. After being reset, pre-query methods can be called on the cursor (sort, limit, etc.) and subsequent calls to next, has_next, or all will re-query the database.


    while ($cursor->has_next) {

Checks if there is another result to fetch.


    while (my $object = $cursor->next) {

Returns the next object in the cursor. Will automatically fetch more data from the server if necessary. Returns undef if no more data is available.


Returns a hash of information about this cursor. Currently the fields are:


The server-side id for this cursor. A cursor_id of 0 means that there are no more batches to be fetched.


The number of results returned so far.


The index of the result the cursor is currently at.


If the database could not find the cursor or another error occurred, flag may be set (depending on the error). See for a full list of flag values.


The index of the result that the current batch of results starts at.


    my @objects = $cursor->all;

Returns a list of all objects in the result.

read_preference ($mode, $tagsets)

    my $cursor = $coll->find()->read_preference(MongoDB::MongoClient->PRIMARY_PREFERRED, [{foo => 'bar'}]);

Sets read preference for the cursor's connection. The $mode argument should be a constant in MongoClient (PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED). The $tagsets specify selection criteria for secondaries in a replica set and should be an ArrayRef whose array elements are HashRefs. This is a convenience method which is identical in function to "read_preference" in MongoDB::MongoClient. In order to use read preference, "find_master" in MongoDB::MongoClient must be set. For core documentation on read preference see

Returns $self so that this method can be chained.


  Kristina Chodorow <>


  • David Golden <>

  • Mike Friedman <>

  • Kristina Chodorow <>

  • Florian Ragwitz <>


This software is Copyright (c) 2014 by MongoDB, Inc..

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004