MongoDB::Cursor(3pm)
β¨ 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). Seehttp://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol#MongoWireProtocol-OPREPLYfor 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>
π COPYRIGHT AND LICENSE π
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
- debian trixie: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu resolute: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- ubuntu stonking: libmongodb-perl 2.2.2-3 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms