MongoD...Client(3pm)
okay bestie, welcome to the MongoDB::MongoClient(3pm) page π
β¨ NAME β¨
MongoDB::MongoClient β a connection to a MongoDB server or multi-server deployment. it's giving main character but for your whole DB setup π
π VERSION π
version v2.2.2 β¨
πΈ SYNOPSIS πΈ
okay so here's the vibe:
use MongoDB; # also loads MongoDB::MongoClient
# connect to localhost:27017
my $client = MongoDB::MongoClient->new;
# connect to specific host and port
my $client = MongoDB::MongoClient->new(
host => "mongodb://mongo.example.com:27017"
);
# connect to a replica set (set name *required*)
my $client = MongoDB::MongoClient->new(
host => "mongodb://mongo1.example.com,mongo2.example.com",
replica_set_name => 'myset',
);
# connect to a replica set with URI (set name *required*)
my $client = MongoDB::MongoClient->new(
host => "mongodb://mongo1.example.com,mongo2.example.com/?replicaSet=myset",
);
my $db = $client->get_database("test");
my $coll = $db->get_collection("people");
$coll->insert({ name => "John Doe", age => 42 });
my @people = $coll->find()->all();
π DESCRIPTION π
The MongoDB::MongoClient class represents a client connection to one or more MongoDB servers. main character energy, fr fr.
By default, it connects to a single server running on the local machine listening on the default port 27017:
# connects to localhost:27017
my $client = MongoDB::MongoClient->new;
It can connect to a database server running anywhere, though:
my $client = MongoDB::MongoClient->new(host => 'example.com:12345');
See the host attribute for more options for connecting to MongoDB. lowkey essential.
MongoDB can be started in authentication mode <http://docs.mongodb.org/manual/core/authentication/>, which requires clients to log in before manipulating data. By default, MongoDB does not start in this mode, so no username or password is required to make a fully functional connection. To configure the client for authentication, see the AUTHENTICATION section. (We'll get there, bestie.)
The actual socket connections are lazy and created on demand. When the client object goes out of scope, all socket will be closed. Note that MongoDB::Database, MongoDB::Collection and related classes could hold a reference to the client as well. Only when all references are out of scope will the sockets be closed.
π ATTRIBUTES π
Now the attributes, bestie. Each one is a little setting you can pass to new or sometimes in the connection string. Let's go.
π host
The host attribute specifies either a single server to connect to (as hostname or hostname:port), or else a connection string URI with a seed list of one or more servers plus connection options.
NOTE: Options specified in the connection string take precedence over options provided as constructor arguments. so if you're double-specifying, the URI wins, periodt.
Defaults to the connection string URI mongodb://localhost:27017.
For IPv6 support, you must have a recent version of IO::Socket::IP installed. This module ships with the Perl core since v5.20.0 and is available on CPAN for older Perls.
β¨ app_name
This attribute specifies an application name that should be associated with this client. The application name will be communicated to the server as part of the initial connection handshake, and will appear in connection-level and operation-level diagnostics on the server generated on behalf of this client. This may be set in a connection string with the appName option.
The default is the empty string, which indicates a lack of an application name.
The application name must not exceed 128 bytes. (so keep it cute and short, bestie.)
π auth_mechanism
This attribute determines how the client authenticates with the server. Valid values are:
NONEDEFAULTMONGODB-CRMONGODB-X509GSSAPIPLAINSCRAM-SHA-1
If not specified, then if no username or authSource URI option is provided, it defaults to NONE. Otherwise, it is set to DEFAULT, which chooses SCRAM-SHA-1 if available or MONGODB-CR otherwise.
This may be set in a connection string with the authMechanism option.
π¦ auth_mechanism_properties
This is an optional hash reference of authentication mechanism specific properties. See AUTHENTICATION for details.
This may be set in a connection string with the authMechanismProperties option. If given, the value must be key/value pairs joined with a :. Multiple pairs must be separated by a comma. If : or , appear in a key or value, they must be URL encoded.
π bson_codec
An object that provides the encode_one and decode_one methods, such as from BSON. It may be initialized with a hash reference that will be coerced into a new BSON object.
If not provided, a BSON object with default values will be generated.
π compressors
An array reference of compression type names. Currently, zlib, zstd and snappy are supported.
πΈ zlib_compression_level
An integer from -1 to 9 specifying the compression level to use when compression is set to zlib.
Note: When the special value -1 is given, the default compression level will be used.
π§ connect_timeout_ms
This attribute specifies the amount of time in milliseconds to wait for a new connection to a server.
The default is 10,000 ms.
If set to a negative value, connection operations will block indefinitely until the server replies or until the operating system TCP/IP stack gives up (e.g. if the name can't resolve or there is no process listening on the target host/port).
A zero value polls the socket during connection and is thus likely to fail except when talking to a local process (and perhaps even then).
This may be set in a connection string with the connectTimeoutMS option.
π db_name
Optional. If an auth_mechanism requires a database for authentication, this attribute will be used. Otherwise, it will be ignored. Defaults to admin.
This may be provided in the connection string URI as a path between the authority and option parameter sections. For example, to authenticate against the admin database (showing a configuration option only for illustration):
mongodb://localhost/admin?readPreference=primary
π«Ά heartbeat_frequency_ms
The time in milliseconds (non-negative) between scans of all servers to check if they are up and update their latency. Defaults to 60,000 ms.
This may be set in a connection string with the heartbeatFrequencyMS option.
π j
If true, the client will block until write operations have been committed to the server's journal. Prior to MongoDB 2.6, this option was ignored if the server was running without journaling. Starting with MongoDB 2.6, write operations will fail if this option is used when the server is running without journaling.
This may be set in a connection string with the journal option as the strings 'true' or 'false'.
π local_threshold_ms
The width of the 'latency window': when choosing between multiple suitable servers for an operation, the acceptable delta in milliseconds (non-negative) between shortest and longest average round-trip times. Servers within the latency window are selected randomly.
Set this to 0 to always select the server with the shortest average round trip time. Set this to a very high value to always randomly choose any known server.
Defaults to 15 ms.
See SERVER SELECTION for more details.
This may be set in a connection string with the localThresholdMS option.
π₯ max_staleness_seconds
The max_staleness_seconds parameter represents the maximum replication lag in seconds (wall clock time) that a secondary can suffer and still be eligible for reads. The default is -1, which disables staleness checks. Otherwise, it must be a positive integer.
Note: this will only be used for server versions 3.4 or greater, as that was when support for staleness tracking was added.
If the read preference mode is 'primary', then max_staleness_seconds must not be supplied.
The max_staleness_seconds must be at least the heartbeat_frequency_ms plus 10 seconds (which is how often the server makes idle writes to the oplog).
This may be set in a connection string with the maxStalenessSeconds option.
β max_time_ms
Specifies the maximum amount of time in (non-negative) milliseconds that the server should use for working on a database command. Defaults to 0, which disables this feature. Make sure this value is shorter than socket_timeout_ms.
Note: this will only be used for server versions2.6or greater, as that was when the$maxTimeMSmeta-operator was introduced.
You are strongly encouraged to set this variable if you know your environment has MongoDB 2.6 or later, as getting a definitive error response from the server is vastly preferred over a getting a network socket timeout.
This may be set in a connection string with the maxTimeMS option.
π monitoring_callback
Specifies a code reference used to receive monitoring events. See MongoDB::Monitoring for more details.
π password
If an auth_mechanism requires a password, this attribute will be used. Otherwise, it will be ignored.
This may be provided in the connection string URI as a username:password pair in the leading portion of the authority section before a @ character. For example, to authenticate as user mulder with password trustno1:
mongodb://mulder:trustno1@localhost
If the username or password have a : or @ in it, they must be URL encoded. An empty password still requires a : character.
π port
If a network port is not specified as part of the host attribute, this attribute provides the port to use. It defaults to 27107.
π read_concern_level
The read concern level determines the consistency level required of data being read.
The default level is undef, which means the server will use its configured default.
If the level is set to local, reads will return the latest data a server has locally.
Additional levels are storage engine specific. See Read Concern <http://docs.mongodb.org/manual/search/?query=readConcern> in the MongoDB documentation for more details.
This may be set in a connection string with the readConcernLevel option.
π¦ read_pref_mode
The read preference mode determines which server types are candidates for a read operation. Valid values are:
primaryprimaryPreferredsecondarysecondaryPreferrednearest
For core documentation on read preference see <http://docs.mongodb.org/manual/core/read-preference/>.
This may be set in a connection string with the readPreference option.
πΈ read_pref_tag_sets
The read_pref_tag_sets parameter is an ordered list of tag sets used to restrict the eligibility of servers, such as for data center awareness. It must be an array reference of hash references.
okay so bestie, before anything else β the way read_pref_tag_sets actually gets used is fully dependent on whatever you set read_pref_mode to. And if read_pref_mode is 'primary'? Then read_pref_tag_sets must not be supplied. Not "shouldn't", not "preferably not" β must not. It's giving hard rule. π
For the core lore on read preference, go read: http://docs.mongodb.org/manual/core/read-preference/
You can also set this in a connection string with the readPreferenceTags option. If you do, the value has to be key/value pairs joined with a ":". Multiple pairs get separated by a comma. And if a ":" or "," shows up inside a key or a value, they must be URL encoded β no exceptions, the parser is not playing. The readPreferenceTags option may appear more than once, and when it does, each document just gets added to the tag set list. Slay.
replica_set_name
This one tells the driver which replica set to connect to. If this string is non-empty, the topology gets treated as a replica set, and every server's replica set name must match it β any that don't match get removed from the topology. Bye. π
Set it in a connection string with the replicaSet option.
retry_reads / retry_writes
Whether the client should use retryable writes for supported commands. Default value is true, which means commands that support retryable writes will get retried on certain errors β like "not master" and "node is recovering" errors. It's giving "bestie fell over, she's getting back up".
Set it in a connection string with the retryWrites option.
Heads up fr fr: this is only supported on MongoDB > 3.6 in Replica Set or Shard Clusters, and it will be ignored on other deployments.
Unacknowledged write operations also do not support retryable writes, even when retry_writes has been enabled. So don't come for me when that doesn't retry. π
The supported single statement write operations are currently as follows:
insert_oneupdate_onereplace_onedelete_onefind_one_and_deletefind_one_and_replacefind_one_and_update
The supported multi statement write operations are as follows:
insert_manybulk_write
The multi statement operations may be either ordered or unordered. Note that for bulk_write operations, the request may not include update_many or delete_many operations. That's the line, bestie, and it does not move.
server_selection_timeout_ms
This attribute says how long, in milliseconds, to wait for a suitable server to be available for a read or write operation. If no server shows up within that window, an exception gets thrown. Iconic dramatic exit. π
The default is 30,000 ms.
See "SERVER SELECTION" for more details.
Set it in a connection string with the serverSelectionTimeoutMS option.
server_selection_try_once
This one controls whether the client makes only a single attempt to find a suitable server for a read or write operation. The default is true.
When true, the client will not use server_selection_timeout_ms. Instead, if the topology information is stale and needs to be checked, or if no suitable server is available, the client makes a single scan of all known servers to try to find a suitable one. One shot, one opportunity. β¨
When false, the client will continually scan known servers until a suitable server is found or serverSelectionTimeoutMS is reached.
See "SERVER SELECTION" for more details.
Set it in a connection string with the serverSelectionTryOnce option.
server_selector
Optional. This takes a function that augments the server selection rules. The function takes as a parameter a list of server descriptions representing the suitable servers for the read or write operation, and returns a list of server descriptions that should still be considered suitable. Most users should just rely on the default server selection algorithm and should not need to set this attribute. Like, respectfully, this is not the main character unless you know exactly why you're here. π
socket_check_interval_ms
If a socket to a server hasn't been used in this many milliseconds, an ismaster command gets issued to check the status of the server before any reads or writes go out. Must be non-negative β do not try it.
The default is 5,000 ms.
Set it in a connection string with the socketCheckIntervalMS option.
socket_timeout_ms
This attribute says how long, in milliseconds, to wait for a reply from the server before a network exception gets issued. β³
The default is 30,000 ms.
If set to a negative value, socket operations will block indefinitely β until the server replies, or until the operating system TCP/IP stack gives up. Whichever comes first, and honestly, may the odds be ever in your favor.
The driver automatically sets the TCP keepalive option when initializing the socket. For keepalive related issues, check the MongoDB documentation for Does TCP keepalive time affect MongoDB Deployments? at https://docs.mongodb.com/v3.2/faq/diagnostics/#does-tcp-keepalive-time-affect-mongodb-deployments
A zero value polls the socket for available data and is thus likely to fail except when talking to a local process (and perhaps even then). Okay so that's a whole cursed setup, just so you know.
Set it in a connection string with the socketTimeoutMS option.
ssl
ssl => 1
ssl => \%ssl_options
This tells the driver you're connecting to an SSL mongodb instance. Secure girl summer. π
You must have IO::Socket::SSL 1.42+ and Net::SSLeay 1.49+ installed for SSL support.
The ssl attribute takes either a boolean value or a hash reference of options to pass to IO::Socket::SSL. For example, to set a CA file to validate the server certificate and set a client certificate for the server to validate, you could set the attribute like this:
ssl => {
SSL_ca_file => "/path/to/ca.pem",
SSL_cert_file => "/path/to/client.pem",
}
If SSL_ca_file is not provided, server certificates are verified against a default list of CAs β either Mozilla::CA or an operating-system-specific default CA file. To disable verification, you can use SSL_verify_mode => 0x00.
You are strongly encouraged to use your own CA file for increased security. Like, strongly. π«Ά
Server hostnames are also validated against the CN name in the server certificate using SSL_verifycn_scheme => 'http'. You can use the scheme 'none' to disable this check.
Disabling certificate or hostname verification is a security risk and is not recommended. Periodt.
This may be set to the string 'true' or 'false' in a connection string with the ssl option, which will enable ssl with default configuration. (See connection string URI for additional TLS configuration options.)
username
Optional username for this client connection. If this field is set, the client will attempt to authenticate when connecting to servers. Depending on the auth_mechanism, the password field or other attributes will need to be set for authentication to succeed. It's giving "you can't just walk in here without your credentials, bestie".
You can also provide this in the connection string URI as a username:password pair in the leading portion of the authority section, before a @ character. For example, to authenticate as user mulder with password trustno1:
mongodb://mulder:trustno1@localhost
If the username or password have a : or @ in it, they must be URL encoded. An empty password still requires a : character. Yes, still. The colon is mandatory. She's non-negotiable. π
w
The client write concern. Here's the whole lineup, no skips:
0β Unacknowledged.MongoClientwill NOT wait for an acknowledgment that the server has received and processed the request. Older documentation may refer to this as "fire-and-forget" mode. This option is not recommended. π©1β Acknowledged.MongoClientwill wait until the primary MongoDB acknowledges the write.2β Replica acknowledged.MongoClientwill wait until at least two replicas (primary and one secondary) acknowledge the write. You can set a higher number for more replicas."all"β All replicas acknowledged."majority"β A majority of replicas acknowledged.
If not set, the server default is used, which is typically "1".
In MongoDB v2.0+, you can "tag" replica members. With "tagging" you can specify a custom write concern. For more information see Data Center Awareness at http://docs.mongodb.org/manual/data-center-awareness/
Set it in a connection string with the w option.
wtimeout
The number of milliseconds an operation should wait for w secondaries to replicate it. β±οΈ
Defaults to 1000 (1 second). If you set this to undef, it could block indefinitely (or until socket timeout is reached). Choose your fighter.
See w above for more information.
Set it in a connection string with the wTimeoutMS option.
β¨ METHODS β¨
read_preference π«Ά
Returns a MongoDB::ReadPreference object constructed from read_pref_mode and read_pref_tag_sets.
The use of read_preference as a mutator has been removed. Read preference is read-only, periodt. If you need a different read preference for a database or collection, you can specify that in get_database or get_collection.
write_concern π
Returns a MongoDB::WriteConcern object constructed from w, write_concern and j.
read_concern πΈ
Returns a MongoDB::ReadConcern object constructed from read_concern_level.
topology_type π¦
Returns an enumerated topology type. If the replica_set_name is set, the value will be either 'ReplicaSetWithPrimary' or 'ReplicaSetNoPrimary' (if the primary is down or not yet discovered). Without replica_set_name, if there is more than one server in the list of hosts, the type will be 'Sharded'.
With only a single host and no replica set name, the topology type will start as 'Direct' until the server is contacted the first time, after which the type will be 'Sharded' for a mongos or 'Single' for standalone server or direct connection to a replica set member.
connect β¨
$client->connect;
Calling this method is unnecessary, because connections are established automatically as needed. It is kept for backwards compatibility. Calling it will check all servers in the deployment which ensures a connection to any that are available.
See reconnect for a method that is useful when using forks or threads.
disconnect π
$client->disconnect;
Drops all connections to servers.
reconnect π
$client->reconnect;
This method closes all connections to the server, as if disconnect were called, and then immediately reconnects. It also clears the session cache. Use this after forking or spawning off a new thread.
topology_status π
$client->topology_status;
$client->topology_status( refresh => 1 );
Returns a hash reference with server topology information like this:
{
'topology_type' => 'ReplicaSetWithPrimary'
'replica_set_name' => 'foo',
'last_scan_time' => '1433766895.183241',
'servers' => [
{
'address' => 'localhost:50003',
'ewma_rtt_ms' => '0.223462326',
'type' => 'RSSecondary'
},
{
'address' => 'localhost:50437',
'ewma_rtt_ms' => '0.268435456',
'type' => 'RSArbiter'
},
{
'address' => 'localhost:50829',
'ewma_rtt_ms' => '0.737782272',
'type' => 'RSPrimary'
}
],
}
If the 'refresh' argument is true, then the topology will be scanned to update server data before returning the hash reference.
start_session π
$client->start_session;
$client->start_session( $options );
Returns a new MongoDB::ClientSession with the supplied options.
will throw a MongoDB::ConfigurationError if sessions are not supported by the connected MongoDB deployment.
the options hash is an optional hash which can have the following keys:
causalConsistencyβ Enable Causally Consistent reads for this session. Defaults to true.
for more information see options in MongoDB::ClientSession.
list_databases π
# get all information on all databases
my @dbs = $client->list_databases;
# get only the foo databases
my @foo_dbs = $client->list_databases({ filter => { name => qr/^foo/ } });
Lists all databases with information on each database. Supports filtering by any of the output fields under the filter argument, such as:
namesizeOnDiskemptyshards
database_names π§
my @dbs = $client->database_names;
# get only the foo database names
my @foo_dbs = $client->database_names({ filter => { name => qr/^foo/ } });
List of all database names on the MongoDB server. Supports filters in the same way as list_databases.
get_database, db π
my $database = $client->get_database('foo');
my $database = $client->get_database('foo', $options);
my $database = $client->db('foo', $options);
Returns a MongoDB::Database instance for the database with the given $name.
It takes an optional hash reference of options that are passed to the MongoDB::Database constructor.
The db method is an alias for get_database.
get_namespace, ns π¦
my $collection = $client->get_namespace('test.foo');
my $collection = $client->get_namespace('test.foo', $options);
my $collection = $client->ns('test.foo', $options);
Returns a MongoDB::Collection instance for the given namespace. The namespace has both the database name and the collection name separated with a dot character.
This is a quick way to get a collection object if you don't need the database object separately.
It takes an optional hash reference of options that are passed to the MongoDB::Collection constructor. The intermediate MongoDB::Database object will be created with default options.
The ns method is an alias for get_namespace.
fsync(\%args) π
$client->fsync();
A function that will force the server to flush all pending writes to the storage layer.
The fsync operation is synchronous by default, to run fsync asynchronously, use the following form:
$client->fsync({async => 1});
The primary use of fsync is to lock the database during backup operations. This will flush all data to the data storage layer and block all write operations until you unlock the database. Note: you can still read while the database is locked.
$conn->fsync({lock => 1});
fsync_unlock π
$conn->fsync_unlock();
Unlocks a database server to allow writes and reverses the operation of a $conn->fsync({lock => 1}); operation.
watch π
Watches for changes on the cluster.
Perform an aggregation with an implicit initial $changeStream stage and returns a MongoDB::ChangeStream result which can be used to iterate over the changes in the cluster. This functionality is available since MongoDB 4.0.
my $stream = $client->watch();
my $stream = $client->watch( \@pipeline );
my $stream = $client->watch( \@pipeline, \%options );
while (1) {
# This inner loop will only run until no more changes are
# available.
while (my $change = $stream->next) {
# process $change
}
}
The returned stream will not block forever waiting for changes. If you want to respond to changes over a longer time use maxAwaitTimeMS and regularly call next in a loop.
See watch in MongoDB::Collection for details on usage and available options.
π DEPLOYMENT TOPOLOGY π
MongoDB can operate as a single server or as a distributed system. One or more servers that collectively provide access to a single logical set of MongoDB databases are referred to as a deployment.
There are three types of deployments:
- Single server β a stand-alone mongod database
- Replica set β a set of mongod databases with data replication and fail-over capability
- Sharded cluster β a distributed deployment that spreads data across one or more shards, each of which can be a replica set. Clients communicate with a mongos process that routes operations to the correct share.
The state of a deployment, including its type, which servers are members, the server types of members and the round-trip network latency to members is referred to as the topology of the deployment.
To the greatest extent possible, the MongoDB driver abstracts away the details of communicating with different deployment types. It determines the deployment topology through a combination of the connection string, configuration options and direct discovery communicating with servers in the deployment.
π CONNECTION STRING URI π
okay so MongoDB uses a lil pseudo-URI connection string to tell the driver which server(s) to hit and how to behave. it's giving β¨just enough structureβ¨.
NOTE: any non-printable ASCII characters should be UTF-8 encoded and converted into URL-escaped characters. no shortcuts bestie.
So if you wanna connect to more than one database server, you hand it host or host:port pairs as a comma separated list:
mongodb://host1[:port1][,host2[:port2],...[,hostN[:portN]]]
That lil list right there? It's officially called the "seed list". π± You can throw an arbitrary number of hosts in there, go wild. And if you don't give a port for a host, it defaults to 27017 β that's the house default, no cap.
If you've got multiple hosts in the seed list (or the driver discovers more while talking to servers in the seed list), they must all be replica set members, OR they must all be mongos servers for a sharded cluster. no mixing, that's the vibe check. π
A replica set MUST have the replicaSet option set to the replica set name. like, mandatory mandatory.
If there's only a single host in the seed list and replicaSet is not provided, the deployment gets treated as a single server deployment and every single read and write goes to that one host. simple life. π¦
π Pro tip from your girl: providing a replica set member as a single host without the set name is literally how you get a "direct connection" for doing administrative activities on that server. that's the move.
The connection string may also carry a username and password:
mongodb://username:password@host1:port1,host2:port2
and yes, the username and password must be URL-escaped. don't be out here raw-dogging special characters. π
You can also pass an optional database name for authentication:
mongodb://username:password@host1:port1,host2:port2/my_database
and finally (the fun part), connection string options can be given as URI attribute pairs in a query string:
mongodb://host1:port1,host2:port2/?ssl=1&wtimeoutMS=1000
mongodb://username:password@host1:port1,host2:port2/my_database?ssl=1&wtimeoutMS=1000
so what are the currently supported connection string options? buckle up bestie, here's the whole roster, every single one, no skips:
appNameauthMechanismauthMechanismPropertiesauthSourcecompressorsconnectconnectTimeoutMSheartbeatFrequencyMSjournallocalThresholdMSmaxStalenessSecondsmaxTimeMSreadConcernLevelreadPreferencereadPreferenceTagsreplicaSetretryReadsretryWritesserverSelectionTimeoutMSserverSelectionTryOncesocketCheckIntervalMSsocketTimeoutMSssltls(an alias forsslβ they're the same thing, twins fr π―)tlsAllowInvalidCertificatestlsAllowInvalidHostnamestlsCAFiletlsCertificateKeyFiletlsCertificateKeyFilePasswordtlsInsecurewwTimeoutMSzlibCompressionLevel
NOTE: Options specified in the connection string take precedence over options provided as constructor arguments. yes, the URI wins. the constructor gets overruled. it's giving main character energy for real. π
Wanna go deeper on the URI format and all these options? the official MongoDB documentation on connection strings has you covered: <http://docs.mongodb.org/manual/reference/connection-string/>. go read it, it's a whole thing. β¨
π― SERVER SELECTION π
For a single server deployment, or a direct connection to a mongod or mongos, literally all reads and writes are sent to that server. Any read-preference is ignored. straight up not invited to the party. π
When you're connected to a deployment with multiple servers β like a replica set or sharded cluster β the driver picks a server for operations based on:
- the type of operation (read or write),
- the application-provided server selector,
- the types of servers available,
- and a read preference.
For a replica set deployment: writes go to the primary (if it's available), and reads go to a server based on the read_preference attribute β which defaults to sending reads to the primary. want the whole story? see MongoDB::ReadPreference. π
For a sharded cluster: reads and writes get distributed across the mongos servers in the seed list. Any read preference is passed through to the mongos and used by it when executing reads against shards. teamwork makes the dream work. π«Ά
So if multiple servers can service an operation (say, multiple mongos servers, or multiple replica set members), the driver narrows it down by filtering with the server selector and then picks at random from within the "latency window". And the window rules are:
- The server with the shortest average round-trip time (RTT) is always in the window. β
- Any servers with an average round-trip time less than or equal to the shortest RTT plus the
local_threshold_msare also in the window.
If a suitable server isn't immediately available, what happens next all depends on the server_selection_try_once option:
- If that option is true, the driver performs a single topology scan. Afterwards, if a suitable server is available, it gets returned; otherwise, an exception is thrown. π one shot, no redo.
- If that option is false, the driver does topology scans repeatedly, hunting for a suitable server. When more than
server_selection_timeout_msmilliseconds have elapsed since the start of server selection and still no suitable server has been found, an exception gets thrown.
Note: the actual maximum wait time for server selection could be as long as server_selection_timeout_ms plus the amount of time required to do a topology scan. so don't @ me when it takes a lil extra. π°οΈ
π SERVER MONITORING AND FAILOVER π₯
When the client first needs to find a server for a database operation, all servers from the host attribute get scanned to figure out which servers to monitor. If the deployment is a replica set, additional hosts may be discovered along the way. Invalid hosts get dropped. bye bestie, blocked. βοΈ
After that initial scan, whenever the servers haven't been checked in heartbeat_frequency_ms milliseconds, the scan gets repeated. This amortizes monitoring time over many operations β efficient queen behavior. π
Additionally, if a socket has been sitting idle for a while, it gets checked before being used for an operation.
Now here's the sad part π β if a server operation fails because of a "not master" or "node is recovering" error, or if there's a network error or a timeout, then that server gets flagged as unavailable and an exception will be thrown. Want the tea on exception types? See MongoDB::Errors.
If the error is caught and handled, the next operation will rescan all servers immediately to update its view of the topology. The driver can keep functioning as long as servers are suitable per SERVER SELECTION. resilient king. π
β οΈ big important thing: when catching an exception, you the user must determine whether or not your application should retry an operation β based on the specific operation attempted and other use-case-specific considerations. this is not a copy-paste-and-pray situation. For automating retries despite exceptions, consider using the Try::Tiny::Retry module. that's the tool for that job. π οΈ
π TRANSPORT LAYER SECURITY π
Warning: industry best practices, and some regulations, require the use of TLS 1.1 or newer. this is not optional energy, this is compliance energy. π
Some operating systems or versions may not provide an OpenSSL version new enough to support the latest TLS protocols. If your OpenSSL library version number is less than 1.0.1, then support for TLS 1.1 or newer is simply not available. Contact your operating system vendor for a solution, or upgrade to a newer operating system distribution. do not fight it, just upgrade. π¦
Also see the documentation for Net::SSLeay for the details on installing and compiling against OpenSSL. it's all in there.
TLS connections in the driver rely on the default settings provided by IO::Socket::SSL, but they let you pass custom configuration to it. please read its documentation carefully to see how to control your TLS configuration β carefully, bestie, not skim-read. ππ
π AUTHENTICATION
So the MongoDB server ships with a whole lil lineup of authentication mechanisms, bestie β though some of them are Enterprise-only, so check your edition before you get your hopes up π .
Client-side auth is your girl's call via the auth_mechanism attribute, and it takes exactly one of these values:
β οΈ NOTE: MONGODB-CR was deprecated with the release of MongoDB 3.6 and is no longer supported by MongoDB 4.0. It's giving legacy, fr fr.
MONGODB-CRβ legacy username-password challenge-response (< 4.0)SCRAM-SHA-1β secure username-password challenge-response (3.0+)MONGODB-X509β SSL client certificate authentication (2.6+)PLAINβ LDAP authentication via SASL PLAIN (Enterprise only)GSSAPIβ Kerberos authentication (Enterprise only)
Which one you reach for depends entirely on how the server is configured β no cap. Peep the core docs on authentication: <http://docs.mongodb.org/manual/core/access-control/>.
Deets for each mechanism are right below, adore π«Ά
π MONGODB-CR and SCRAM-SHA-1 (for username/password)
These two want a username and a password, and you can hand them over either as constructor attributes or tucked inside the host connection string. Either way, slay.
If you give a username but don't specify a mechanism, the client will use SCRAM-SHA-1 on version 3.0-or-later servers, and will fall back to MONGODB-CR for the older ones. It just knows β¨
my $mc = MongoDB::MongoClient->new(
host => "mongodb://mongo.example.com/",
username => "johndoe",
password => "trustno1",
);
my $mc = MongoDB::MongoClient->new(
host => "mongodb://johndoe:trustno1@mongo.example.com/",
);
Usernames and passwords get UTF-8 encoded before use, obvi. And the password is never sent over the wire β only a secure digest goes out. Privacy icon behavior π
The SCRAM-SHA-1 mechanism is the Salted Challenge Response Authentication Mechanism, defined in RFC 5802 <http://tools.ietf.org/html/rfc5802>.
The default database for authentication is 'admin'. Wanna use a different database name? Say so with the db_name attribute, or slip it into the connection string:
db_name => auth_db
mongodb://johndoe:trustno1@mongo.example.com/auth_db
π MONGODB-X509 (for SSL client certificate)
X509 auth requires SSL support (IO::Socket::SSL), requires a client certificate to be configured in the ssl parameters, and requires you to explicitly say "MONGODB-X509" as the mechanism. Three requirements, all non-negotiable bestie π€
my $mc = MongoDB::MongoClient->new(
host => "mongodb://sslmongo.example.com/",
ssl => {
SSL_ca_file => "certs/ca.pem",
SSL_cert_file => "certs/client.pem",
},
auth_mechanism => "MONGODB-X509",
);
πΈ Note: Since MongoDB Perl driver v1.8.0, you no longer need to specify a username parameter for X509 authentication β the username gets extracted automatically from the certificate. The way that it just does that for you?? Obsessed.
π§Ύ PLAIN (for LDAP)
This one needs a username and a password, and both get UTF-8 encoded before use. The auth_mechanism param must be given as a constructor attribute or inside the host connection string:
my $mc = MongoDB::MongoClient->new(
host => "mongodb://mongo.example.com/",
username => "johndoe",
password => "trustno1",
auth_mechanism => "PLAIN",
);
my $mc = MongoDB::MongoClient->new(
host => "mongodb://johndoe:trustno1@mongo.example.com/authMechanism=PLAIN",
);
π« GSSAPI (for Kerberos)
Kerberos auth needs the CPAN module Authen::SASL plus a GSSAPI-capable backend. No backend, no ticket, no entry β sorry babe ποΈ
On Debian systems, Authen::SASL may be available as libauthen-sasl-perl; on RHEL systems, it may be available as perl-Authen-SASL.
The Authen::SASL::Perl backend comes bundled with Authen::SASL and requires the GSSAPI CPAN module for GSSAPI support. On Debian systems, this may be available as libgssapi-perl; on RHEL systems, this may be available as perl-GSSAPI.
Installing the GSSAPI module from CPAN instead of an OS package requires libkrb5 and the krb5-config utility (available for Debian/RHEL systems in the libkrb5-dev package).
Alternatively, the Authen::SASL::XS or Authen::SASL::Cyrus modules may be used. Both rely on Cyrus libsasl. Authen::SASL::XS is preferred, but is not yet available as an OS package. Authen::SASL::Cyrus is available on Debian as libauthen-sasl-cyrus-perl and on RHEL as perl-Authen-SASL-Cyrus.
Installing Authen::SASL::XS or Authen::SASL::Cyrus from CPAN requires libsasl. On Debian systems, it is available from libsasl2-dev; on RHEL, it is available in cyrus-sasl-devel.
To use the GSSAPI mechanism, first run kinit to authenticate with the ticket granting service:
$ kinit johndoe@EXAMPLE.COM
Then configure MongoDB::MongoClient with the principal name as the username parameter and specify 'GSSAPI' as the auth_mechanism:
my $mc = MongoDB::MongoClient->new(
host => 'mongodb://mongo.example.com',
username => 'johndoe@EXAMPLE.COM',
auth_mechanism => 'GSSAPI',
);
Both can be specified in the host connection string too β just keep in mind that the '@' in the principal name must be encoded as "%40" (iykyk, URI escaping is a whole thing):
my $mc = MongoDB::MongoClient->new(
host =>
'mongodb://johndoe%40EXAMPLE.COM@mongo.example.com/?authMechanism=GSSAPI',
);
The default service name is 'mongodb'. Wanna change it? Use the auth_mechanism_properties attribute, or do it in the connection string:
auth_mechanism_properties => { SERVICE_NAME => 'other_service' }
mongodb://.../?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:other_service
π§΅ THREAD-SAFETY AND FORK-SAFETY
You MUST call the reconnect method on any MongoDB::MongoClient objects after forking or spawning a thread. Not optional, not a suggestion, it's giving mandatory π¨
π 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β¦ tread carefully, bestie.
π 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 a wrap on the whole page, angel π This beauty was rendered by perl v5.40.1 on 2025-04-03, and yes β the footer is still out here spelling the name MongoD...Client(3pm) because manpages truncate things and we forgive them π Slay, go write some queries π¦β¨
π¦ 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