MongoDB::Cursor(3pm)

πŸ“¦
version 2.2.2 Β· 5 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

✨ MongoDB::Cursor ✨

okay so bestie, welcome to MongoDB::Cursor πŸ’– straight out of the User Contributed Perl Documentation (3pm) corner of your terminal. She's a lazy cursor for Mongo query results β€” and by "lazy" we mean she literally does not lift a finger until you ask her to. That's not a flaw, that's ✨main character energy✨.


🌸 VERSION 🌸

version v2.2.2 β€” she's serving v2.2.2, no cap.


πŸŽ€ SYNOPSIS πŸŽ€

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

my @objects = $cursor->all;

that's the vibe, that's the whole vibe. πŸ’…


πŸ¦‹ USAGE πŸ¦‹

🌈 Multithreading 🌈

NOTE: per the threads documentation, use of Perl threads is discouraged by the maintainers of Perl, and the MongoDB Perl driver does not test or provide support for use with threads. so like… don't. πŸ™ˆ

Cursors get cloned in threads, but not reset. Iterating the same cursor from multiple threads will give you unpredictable results 😭 β€” so only iterate from a single thread, bestie. one thread, one cursor, one happy life.


πŸ’œ ATTRIBUTES πŸ’œ

⭐ started_iterating

A boolean that tells you whether this cursor has already queried the database yet. Real talk: methods that modify the query will complain if you call them after the database has been queried. she has boundaries now.


πŸ”₯ QUERY MODIFIERS πŸ”₯

These methods modify the query that's gonna get run. An exception will be thrown if you call them after results have been iterated. so call them first, okay? 😌

πŸ‘‘ immortal

$cursor->immortal(1);

Ordinarily a cursor "dies" on the database server after a certain length of time (approximately 10 minutes), so that inactive cursors stop hogging all the resources. This option says: no. she does not die until all her results have been fetched, or until she goes out of scope in Perl. iconic behaviour honestly.

Boolean value, defaults to 0.

Note: immortal only touches the server-side timeout. If you're getting client-side timeouts, you'll need to change your client configuration instead. Go peep "max_time_ms" in MongoDB::MongoClient and "socket_timeout_ms" in MongoDB::MongoClient.

Returns this cursor for chaining operations. 🫢

πŸ“ fields

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

Selects which fields come back. The default is all fields. When you specify fields, _id is returned by default β€” but you can switch that off by explicitly setting it to "0", like "_id => 0". The argument has to be either a hash reference or a Tie::IxHash object.

For the details, see Limit fields to return at http://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/ in the MongoDB documentation.

Returns this cursor for chaining operations. πŸ’–

πŸ’… sort

# sort by name, descending
$cursor->sort([name => -1]);

Adds a sort to the query. The argument is either a hash reference, a Tie::IxHash, or an array reference of key/value pairs. And because hash references are not ordered, do not use them for more than one key. one key or ordered structure, that's the rule. ✨

Returns this cursor for chaining operations.

🌸 limit

$cursor->limit(20);

Sets the cursor to return a maximum of N results. that's it, that's the method.

Returns this cursor for chaining operations.

🧚 max_await_time_ms

$cursor->max_await_time_ms( 500 );

The maximum amount of time, in milliseconds, for the server to wait on new documents to satisfy a tailable cursor query. This only applies to a cursor of type 'tailble_await'. (yes, that spelling, we don't make the rules πŸ’€) It's ignored if the cursor isn't a 'tailable_await' cursor, or if the server version is less than version 3.2.

Returns this cursor for chaining operations.

⭐ max_time_ms

$cursor->max_time_ms( 500 );

Causes the server to abort the operation if the specified time in milliseconds is exceeded. time's up, babes.

Returns this cursor for chaining operations.

πŸ’€ tailable

$cursor->tailable(1);

Sets whether 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 stuff gets added to a collection. they're basically the group chat that never sleeps. 😭

They're often used for getting log messages.

Boolean value, defaults to 0.

If you want your tailable cursor to block for a few seconds, use "tailable_await" instead. Note: calling this with a false value disables tailing, even if "tailable_await" was previously called. πŸ™ˆ

Returns this cursor for chaining operations.

🌈 tailable_await

$cursor->tailable_await(1);

Sets a cursor to be tailable and block for a few seconds if no data is immediately available.

Boolean value, defaults to 0.

If you want the tailable cursor without the blocking, use "tailable" instead. Note: calling this with a false value disables tailing, even if "tailable" was previously called. πŸ‘‘

πŸŽ€ skip

$cursor->skip( 50 );

Skips the first N results. no thoughts, just skipping.

Returns this cursor for chaining operations.

πŸ¦‹ hint

Hint the query to use a specific index by name:

$cursor->hint("index_name");

Hint the query to use an index based on individual keys and direction:

$cursor->hint([field_1 => 1, field_2 => -1, field_3 => 1]);

Use of a hash reference should be avoided except for single-key indexes. ⚠️

The hint must be a string or an ordered document.

Returns this cursor for chaining operations.

πŸ’œ partial

$cursor->partial(1);

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. lowkey graceful, honestly.

Boolean value, defaults to 0.

Returns this cursor for chaining operations.

πŸ”₯ read_preference

$cursor->read_preference($read_preference_object);
$cursor->read_preference('secondary', [{foo => 'bar'}]);

Sets the read preference for the cursor's connection.

If you give it a single argument that's a MongoDB::ReadPreference object, the read preference gets set to that object. Otherwise it takes positional arguments: the read preference mode and a tag set list, and those have to be a valid mode and tag set list as described in the MongoDB::ReadPreference documentation.

Returns this cursor for chaining operations.


πŸ” QUERY INTROSPECTION AND RESET πŸ”

These methods run introspection methods on the query conditions and modifiers stored inside the cursor object. it's giving "let me look at myself" πŸ’…

πŸ‘‘ explain

my $explanation = $cursor->explain;

This tells 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. receipts, basically. 🧾✨

See also the core documentation on explain at http://dochub.mongodb.org/core/explain.


🌟 QUERY ITERATION 🌟

These methods let you iterate over results. the moment we've all been waiting for.

🌸 result

my $result = $cursor->result;

This method executes the query and returns a MongoDB::QueryResult object with the results.

The "has_next", "next", and "all" methods call "result" internally, which means the query executes "on demand". she's lazy, we've established this. 😌

Iterating with a MongoDB::QueryResult object directly instead of a MongoDB::Cursor will be slightly faster, since the MongoDB::Cursor methods below just internally call the corresponding method on the result object. speed, but make it tiny.

πŸŽ€ has_next

while ($cursor->has_next) {
    ...
}

Checks if there's another result to fetch. Will automatically fetch more data from the server if necessary. 🫢

⭐ next

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. 😭

πŸ¦‹ batch

while (my @batch = $cursor->batch) {
    ...
}

Returns the next batch of data from the cursor. Will automatically fetch more data from the server if necessary. Returns an empty list if no more data is available.

πŸ’– all

my @objects = $cursor->all;

Returns a list of all objects in the result. all of them. every single one. πŸ‘‘

🌈 reset

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

🧚 info

Returns a hash of information about this cursor. This is intended for debugging purposes, and users should not rely on the contents of this method for production use. ⚠️ Currently the fields are:

  • "cursor_id" -- the server-side id for this cursor. See below for details.
  • "num" -- the number of results received from the server so far
  • "at" -- the (zero-based) index of the document that will be returned next from "next"
  • "flag" -- if the database could not find the cursor or another error occurred, "flag" may contain a hash reference of flags set in the response (depending on the error). See http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol#MongoWireProtocol-OPREPLY for a full list of flag values.
  • "start" -- the index of the result that the current batch of results starts at.

If the cursor has not yet executed, only the "num" field will be returned, with a value of 0.

The "cursor_id" could appear in one of three forms:

  • MongoDB::CursorID object (a blessed reference to an 8-byte string)
  • A perl scalar (an integer)
  • A Math::BigInt object (64 bit integer on 32-bit perl)

When the "cursor_id" is zero, there are no more results to fetch. πŸ’€


πŸ’œ SEE ALSO πŸ’œ

Core documentation on cursors: http://dochub.mongodb.org/core/cursors.


πŸ‘‘ AUTHORS πŸ‘‘

  • David Golden <david@mongodb.com>
  • Rassi <rassi@mongodb.com>
  • Mike Friedman <friedo@friedo.com>
  • Kristina Chodorow <k.chodorow@gmail.com>
  • Florian Ragwitz <rafl@debian.org>

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

This is free software, licensed under:

The Apache License, Version 2.0, January 2004

and that's the whole page bestie, no cap πŸ’… this was perl v5.40.1, dated 2025-04-03, and produced by MongoDB::Cursor(3pm) β€” go forth and iterate responsibly, one thread at a time πŸŽ€βœ¨πŸ¦‹

πŸ“¦ where this page comes from