MongoD...ession(3pm)
π MongoDB::ClientSession π β the session & transaction management era β¨
So bestie, this is MongoDB::ClientSession, straight outta the User Contributed Perl Documentation, part of the MongoDB Perl driver and honestly? It's giving main character energy. It's the lil class that holds an active session for your client, it runs on MongoDB 3.6+ (sessions support is new with MongoDB 3.6, iykyk), and it works in replica set and sharded MongoDB clusters. π¦
β¨ NAME β¨
MongoDB::ClientSession β MongoDB session and transaction management. periodt. π
πΈ VERSION πΈ
version v2.2.2 β that's the one, no cap.
π SYNOPSIS π
my $session = $client->start_session( $options );
# use session in operations
my $result = $collection->find( { id => 1 }, { session => $session } );
# use sessions for transactions
$session->start_transaction;
...
if ( $ok ) {
$session->commit_transaction;
}
else {
$session->abort_transaction;
}
Look at that. Chef's kiss. ππ
π DESCRIPTION π
Okay so real talk: this class encapsulates an active session for use with the current client. Sessions support is new with MongoDB 3.6, and can be used in replica set and sharded MongoDB clusters. That's it, that's the vibe. π
π«Ά Explicit and Implicit Sessions π«Ά
If you specifically apply a session to an operation, then the operation will be performed with that session id. Slay, that's explicit.
If you do not provide a session for an operation, and the server supports sessions, then an implicit session will be created and used for this operation. The driver just handles it for you, lowkey the bestie behavior.
The only exception to this is for unacknowledged writes β the driver will not provide an implicit session for this, and if you provide a session, then the driver will raise an error. So don't do that. Just don't. π
π¦ Cursors π¦
During cursors, if a session is not provided then an implicit session will be created which is then used for the lifetime of the cursor. Cute, right?
If you provide a session, then note that ending the session and then continuing to use the cursor will raise an error. Like, it's over, the cursor is done, move on. π
π§ Thread Safety π§
NOTE: Per 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.
Sessions are NOT thread safe, and should only be used by one thread at a time. Using a session across multiple threads is unsupported and unexpected issues and errors may occur. Also β and this is the wild part β the driver does not even check for multi-threaded use. So it's not gonna catch you. π
π Transactions π
A session may be associated with at most one open transaction (on MongoDB 4.0+). For detailed instructions on how to use transactions with drivers, see the MongoDB manual page: Transactions β https://docs.mongodb.com/master/core/transactions.
β ATTRIBUTES β
πΈ client πΈ
The client this session was created using. Sessions may only be used with the client that created them. Loyalty only, fr fr. π«Ά
βοΈ cluster_time βοΈ
Stores the last received $clusterTime for the client session. This is an opaque value, so to set it use the advance_cluster_time function. Don't try to hand-craft it, bestie, that's not the move.
π options π
Options provided for this particular session. Available options include:
causalConsistencyβ If true, will enablecausalConsistencyfor this session. For more information, see MongoDB documentation on Causal Consistency βhttps://docs.mongodb.com/manual/core/read-isolation-consistency-recency/#causal-consistency. Note thatcausalConsistencydoes not apply for unacknowledged writes. Defaults totrue. β¨defaultTransactionOptionsβ Options to use by default for transactions created with this session. If when creating a transaction, none or only some of the transaction options are defined, these options will be used as a fallback. Defaults to inheriting from the parent client. Seestart_transactionfor available options. π₯
π°οΈ operation_time π°οΈ
The last operation time. This is updated when an operation is performed during this session, or when advance_operation_time is called. Used for causal consistency. Time is literally a construct and this is the construct.
π« METHODS π«
π session_id π
The session id for this particular session. This should be considered an opaque value. If end_session has been called, this returns undef. So like, it's gone gone. π
π get_latest_cluster_time π
my $cluster_time = $session->get_latest_cluster_time;
Returns the latest cluster time, when compared with this session's recorded cluster time and the main client cluster time. If neither is defined, returns undef. Simple as that. π€·ββοΈ
β° advance_cluster_time β°
$session->advance_cluster_time( $cluster_time );
Update the $clusterTime for this session. Stores the value in cluster_time. If the cluster time provided is more recent than the sessions current cluster time, then the session will be updated to this provided value.
Setting the$clusterTimewith a manually crafted value may cause a server error. It is recommended to only use$clusterTimevalues retrieved from database calls. Do not go crafting values by hand, I am begging you. π
β advance_operation_time β
$session->advance_operation_time( $operation_time );
Update the operation_time for this session. If the value provided is more recent than the sessions current operation time, then the session will be updated to this provided value.
Settingoperation_timewith a manually crafted value may cause a server error. It is recommended to only use anoperation_timeretrieved from another session or directly from a database call. Same energy as above. π
π₯ start_transaction π₯
$session->start_transaction;
$session->start_transaction( $options );
Start a transaction in this session. If a transaction is already in progress, or if the driver can detect that the client is connected to a topology that does not support transactions, this method will throw an error. No double-dipping, bestie. π«
A hash reference of options may be provided. Valid keys include:
readConcernβ The read concern to use for the first command in this transaction. If not defined here or in thedefaultTransactionOptionsinoptions, will inherit from the parent client.writeConcernβ The write concern to use for committing or aborting this transaction. As perreadConcern, if not defined here then the value defined indefaultTransactionOptionswill be used, or the parent client if not defined.readPreferenceβ The read preference to use for all read operations in this transaction. If not defined, then will inherit fromdefaultTransactionOptionsor from the parent client. This value will override all other read preferences set in any subsequent commands inside this transaction. It said what it said. πmaxCommitTimeMSβ ThemaxCommitTimeMSspecifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
β¨ commit_transaction β¨
$session->commit_transaction;
Commit the current transaction. This will use the writeConcern set on this transaction. Yass, ship it. π
If called when no transaction is in progress, then this method will throw an error.
If the commit operation encounters an error, an error is thrown. If the error is a transient commit error, the error object will have a label containing UnknownTransactionCommitResult as an element and the commit operation can be retried. This can be checked via the has_error_label:
LOOP: {
eval {
$session->commit_transaction;
};
if ( my $error = $@ ) {
if ( $error->has_error_label("UnknownTransactionCommitResult") ) {
redo LOOP;
}
else {
die $error;
}
}
}
Retry loop go brrr. π
π abort_transaction π
$session->abort_transaction;
Aborts the current transaction. If no transaction is in progress, then this method will throw an error. Otherwise, this method will suppress all other errors (including network and database errors). Yeah, it just eats them. Silently. Iconic but also scary. π
π end_session π
$session->end_session;
Close this particular session and release the session ID for reuse or recycling. If a transaction is in progress, it will be aborted. Has no effect after calling for the first time β so calling it twice is fine, it's just like "yeah I know, we're done here".
This will be called automatically by the object destructor. The driver's got you. π«Ά
π¦ with_transaction π¦
$session->with_transaction($callback, $options);
Execute a callback in a transaction. β¨
This method starts a transaction on this session, executes $callback, and then commits the transaction, returning the return value of the $callback. The $callback will be executed at least once.
If the $callback throws an error, the transaction will be aborted. If less than 120 seconds have passed since calling with_transaction, and the error has a TransientTransactionError label, the transaction will be restarted and the callback will be executed again. Otherwise, the error will be thrown.
If the $callback succeeds, then the transaction will be committed. If an error is thrown from committing the transaction, and it is less than 120 seconds since calling with_transaction, then:
- If the error has a
TransientTransactionErrorlabel, the transaction will be restarted. - If the error has an
UnknownTransactionCommitResultlabel, and is not aMaxTimeMSExpirederror, then the commit will be retried.
If the $callback aborts or commits the transaction, no other actions are taken and the return value of the $callback is returned.
The callback is called with the first (and only) argument being the session, after starting the transaction:
$session->with_transaction( sub {
# this is the same session as used for with_transaction
my $cb_session = shift;
...
}, $options);
To pass arbitrary arguments to the $callback, wrap your callback in a coderef:
$session->with_transaction(sub { $callback->($session, $foo, ...) }, $options);
Warning: you must either use the provided session within the callback, or otherwise pass the session in use to the callback. You must pass the $session as an option to all database operations that need to be included in the transaction. Don't forget it, bestie, or things get weird. π
Warning: The $callback can be called multiple times, so it is recommended to make it idempotent. Make it repeatable, fr fr. π
A hash reference of options may be provided. these are the same as for start_transaction. (Yes, the original said "these" lowercase. We are respecting the source material. π
)
π AUTHORS π
The icons who made this:
- 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>
Give them their flowers, they ate. π
π 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!! This was from perl v5.40.1 and the page was dated 2025-04-03, and yes it's the MongoD...ession(3pm) page you were looking for (the title got a lil truncated by the manpage formatter, happens to everyone, no worries). Go forth and manage your sessions responsibly. Slay, commit, and always end_session. π
β¨π¦
π¦ 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