The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.


MongoDB::MongoClient - A connection to a MongoDB server or multi-server deployment


version v2.2.2


    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://"

    # connect to a replica set (set name *required*)
    my $client = MongoDB::MongoClient->new(
        host => "mongodb://,",
        replica_set_name => 'myset',

    # connect to a replica set with URI (set name *required*)
    my $client = MongoDB::MongoClient->new(
        host => "mongodb://,",

    my $db = $client->get_database("test");
    my $coll = $db->get_collection("people");

    $coll->insert({ name => "John Doe", age => 42 });
    my @people = $coll->find()->all();


The MongoDB::MongoClient class represents a client connection to one or more MongoDB servers.

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 => '');

See the "host" attribute for more options for connecting to MongoDB.

MongoDB can be started in authentication mode, 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.

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.



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.

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.


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.


This attribute determines how the client authenticates with the server. Valid values are:

  • NONE



  • MONGODB-X509




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.


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.


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.


An array reference of compression type names. Currently, zlib, zstd and snappy are supported.


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.


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.


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):



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.


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


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.


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.


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 versions 2.6 or greater, as that was when the $maxTimeMS meta-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.


Specifies a code reference used to receive monitoring events. See MongoDB::Monitoring for more details.


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":


If the username or password have a ":" or "@" in it, they must be URL encoded. An empty password still requires a ":" character.


If a network port is not specified as part of the host attribute, this attribute provides the port to use. It defaults to 27107.


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 in the MongoDB documentation for more details.

This may be set in a connection string with the the readConcernLevel option.


The read preference mode determines which server types are candidates for a read operation. Valid values are:

  • primary

  • primaryPreferred

  • secondary

  • secondaryPreferred

  • nearest

For core documentation on read preference see

This may be set in a connection string with the readPreference option.


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.

The application of read_pref_tag_sets varies depending on the read_pref_mode parameter. If the read_pref_mode is 'primary', then read_pref_tag_sets must not be supplied.

For core documentation on read preference see

This may be set in a connection string with the readPreferenceTags 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. The readPreferenceTags option may appear more than once, in which case each document will be added to the tag set list.


Specifies the replica set name to connect to. If this string is non-empty, then the topology is treated as a replica set and all server replica set names must match this or they will be removed from the topology.

This may be set in a connection string with the replicaSet option.



Whether the client should use retryable writes for supported commands. The default value is true, which means that commands which support retryable writes will be retried on certain errors, such as not master and node is recovering errors.

This may be set in a connection string with the retryWrites option.

Note that this is only supported on MongoDB > 3.6 in Replica Set or Shard Clusters, and will be ignored on other deployments.

Unacknowledged write operations also do not support retryable writes, even when retry_writes has been enabled.

The supported single statement write operations are currently as follows:

  • insert_one

  • update_one

  • replace_one

  • delete_one

  • find_one_and_delete

  • find_one_and_replace

  • find_one_and_update

The supported multi statement write operations are as follows:

  • insert_many

  • bulk_write

The multi statement operations may be ether ordered or unordered. Note that for bulk_write operations, the request may not include update_many or delete_many operations.


This attribute specifies the amount of time in milliseconds to wait for a suitable server to be available for a read or write operation. If no server is available within this time period, an exception will be thrown.

The default is 30,000 ms.

See "SERVER SELECTION" for more details.

This may be set in a connection string with the serverSelectionTimeoutMS option.


This attribute controls whether the client will make 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 the 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 will make a single scan of all known servers to try to find a suitable one.

When false, the client will continually scan known servers until a suitable server is found or the serverSelectionTimeoutMS is reached.

See "SERVER SELECTION" for more details.

This may be set in a connection string with the serverSelectionTryOnce option.


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 rely on the default server selection algorithm and should not need to set this attribute.


If a socket to a server has not been used in this many milliseconds, an ismaster command will be issued to check the status of the server before issuing any reads or writes. Must be non-negative.

The default is 5,000 ms.

This may be set in a connection string with the socketCheckIntervalMS option.


This attribute specifies the amount of time in milliseconds to wait for a reply from the server before issuing a network exception.

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.

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

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

This may be set in a connection string with the socketTimeoutMS option.


    ssl => 1
    ssl => \%ssl_options

This tells the driver that you are connecting to an SSL mongodb instance.

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.

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.

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


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.

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":


If the username or password have a ":" or "@" in it, they must be URL encoded. An empty password still requires a ":" character.


The client write concern.

  • 0 Unacknowledged. MongoClient will 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. MongoClient will wait until the primary MongoDB acknowledges the write.

  • 2 Replica acknowledged. MongoClient will 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

This may be set in a connection string with the w option.


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

See w above for more information.

This may be set in a connection string with the wTimeoutMS option.



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. If you need a different read preference for a database or collection, you can specify that in get_database or get_collection.


Returns a MongoDB::WriteConcern object constructed from "w", "write_concern" and "j".


Returns a MongoDB::ReadConcern object constructed from "read_concern_level".


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.



Calling this method is unnecessary, as 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.



Drops all connections to servers.



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.


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


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


    # 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:

  • name

  • sizeOnDisk

  • empty

  • shards


    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('');
    my $collection = $client->get_namespace('', $options);
    my $collection = $client->ns('', $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.



A function that will forces 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});



Unlocks a database server to allow writes and reverses the operation of a $conn->fsync({lock => 1}); operation.


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.


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.


MongoDB uses a pseudo-URI connection string to specify one or more servers to connect to, along with configuration options.

NOTE: any non-printable ASCII characters should be UTF-8 encoded and converted URL-escaped characters.

To connect to more than one database server, provide host or host:port pairs as a comma separated list:


This list is referred to as the "seed list". An arbitrary number of hosts can be specified. If a port is not specified for a given host, it will default to 27017.

If multiple hosts are given in the seed list or discovered by talking to servers in the seed list, they must all be replica set members or must all be mongos servers for a sharded cluster.

A replica set MUST have the replicaSet option set to the replica set name.

If there is only single host in the seed list and replicaSet is not provided, the deployment is treated as a single server deployment and all reads and writes will be sent to that host.

Providing a replica set member as a single host without the set name is the way to get a "direct connection" for carrying out administrative activities on that server.

The connection string may also have a username and password:


The username and password must be URL-escaped.

A optional database name for authentication may be given:


Finally, connection string options may be given as URI attribute pairs in a query string:


The currently supported connection string options are:

  • appName

  • authMechanism

  • authMechanismProperties

  • authSource

  • compressors

  • connect

  • connectTimeoutMS

  • heartbeatFrequencyMS

  • journal

  • localThresholdMS

  • maxStalenessSeconds

  • maxTimeMS

  • readConcernLevel

  • readPreference

  • readPreferenceTags

  • replicaSet

  • retryReads

  • retryWrites

  • serverSelectionTimeoutMS

  • serverSelectionTryOnce

  • socketCheckIntervalMS

  • socketTimeoutMS

  • ssl

  • tls (an alias for ssl)

  • tlsAllowInvalidCertificates

  • tlsAllowInvalidHostnames

  • tlsCAFile

  • tlsCertificateKeyFile

  • tlsCertificateKeyFilePassword

  • tlsInsecure

  • w

  • wTimeoutMS

  • zlibCompressionLevel

NOTE: Options specified in the connection string take precedence over options provided as constructor arguments.

See the official MongoDB documentation on connection strings for more on the URI format and connection string options:


For a single server deployment or a direct connection to a mongod or mongos, all reads and writes are sent to that server. Any read-preference is ignored.

When connected to a deployment with multiple servers, such as a replica set or sharded cluster, the driver chooses a server for operations based on the type of operation (read or write), application-provided server selector, the types of servers available and a read preference.

For a replica set deployment, writes are sent to the primary (if available) and reads are sent to a server based on the "read_preference" attribute, which defaults to sending reads to the primary. See MongoDB::ReadPreference for more.

For a sharded cluster reads and writes are distributed across mongos servers in the seed list. Any read preference is passed through to the mongos and used by it when executing reads against shards.

If multiple servers can service an operation (e.g. multiple mongos servers, or multiple replica set members), one is chosen by filtering with server selector and then at random from within the "latency window". 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_ms" are also in the latency window.

If a suitable server is not immediately available, what happens next depends on the "server_selection_try_once" option.

If that option is true, a single topology scan will be performed. Afterwards if a suitable server is available, it will be returned; otherwise, an exception is thrown.

If that option is false, the driver will do topology scans repeatedly looking for a suitable server. When more than "server_selection_timeout_ms" milliseconds have elapsed since the start of server selection without a suitable server being found, an exception is thrown.

Note: the actual maximum wait time for server selection could be as long server_selection_timeout_ms plus the amount of time required to do a topology scan.


When the client first needs to find a server for a database operation, all servers from the "host" attribute are scanned to determine which servers to monitor. If the deployment is a replica set, additional hosts may be discovered in this process. Invalid hosts are dropped.

After the initial scan, whenever the servers have not been checked in "heartbeat_frequency_ms" milliseconds, the scan will be repeated. This amortizes monitoring time over many of operations. Additionally, if a socket has been idle for a while, it will be checked before being used for an operation.

If a server operation fails because of a "not master" or "node is recovering" error, or if there is a network error or timeout, then the server is flagged as unavailable and exception will be thrown. See MongoDB::Errors for exception types.

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 continue to function as long as servers are suitable per "SERVER SELECTION".

When catching an exception, users must determine whether or not their application should retry an operation based on the specific operation attempted and other use-case-specific considerations. For automating retries despite exceptions, consider using the Try::Tiny::Retry module.


Warning: industry best practices, and some regulations, require the use of TLS 1.1 or newer.

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 not available. Contact your operating system vendor for a solution or upgrade to a newer operating system distribution.

See also the documentation for Net::SSLeay for details on installing and compiling against OpenSSL.

TLS connections in the driver rely on the default settings provided by IO::Socket::SSL, but allow you to pass custom configuration to it. Please read its documentation carefully to see how to control your TLS configuration.


The MongoDB server provides several authentication mechanisms, though some are only available in the Enterprise edition.

MongoDB client authentication is controlled via the "auth_mechanism" attribute, which takes one of the following values:

NOTE: MONGODB-CR was deprecated with the release of MongoDB 3.6 and is no longer supported by MongoDB 4.0.

  • 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)

The mechanism to use depends on the authentication configuration of the server. See the core documentation on authentication:

Usage information for each mechanism is given below.

MONGODB-CR and SCRAM-SHA-1 (for username/password)

These mechanisms require a username and password, given either as constructor attributes or in the host connection string.

If a username is provided and an authentication mechanism is not specified, the client will use SCRAM-SHA-1 for version 3.0 or later servers and will fall back to MONGODB-CR for older servers.

    my $mc = MongoDB::MongoClient->new(
        host => "mongodb://",
        username => "johndoe",
        password => "trustno1",

    my $mc = MongoDB::MongoClient->new(
        host => "mongodb://",

Usernames and passwords will be UTF-8 encoded before use. The password is never sent over the wire -- only a secure digest is used. The SCRAM-SHA-1 mechanism is the Salted Challenge Response Authentication Mechanism defined in RFC 5802.

The default database for authentication is 'admin'. If another database name should be used, specify it with the db_name attribute or via the connection string.

    db_name => auth_db


MONGODB-X509 (for SSL client certificate)

X509 authentication requires SSL support (IO::Socket::SSL), requires that a client certificate be configured in the ssl parameters, and requires specifying the "MONGODB-X509" authentication mechanism.

    my $mc = MongoDB::MongoClient->new(
        host => "mongodb://",
        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 will be extracted automatically from the certificate.


This mechanism requires a username and password, which will be UTF-8 encoded before use. The auth_mechanism parameter must be given as a constructor attribute or in the host connection string:

    my $mc = MongoDB::MongoClient->new(
        host => "mongodb://",
        username => "johndoe",
        password => "trustno1",
        auth_mechanism => "PLAIN",

    my $mc = MongoDB::MongoClient->new(
        host => "mongodb://",

GSSAPI (for Kerberos)

Kerberos authentication requires the CPAN module Authen::SASL and a GSSAPI-capable backend.

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 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, it may be available as perl-GSSAPI.

Installing the GSSAPI module from CPAN rather than 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 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

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://',
        username => 'johndoe@EXAMPLE.COM',
        auth_mechanism => 'GSSAPI',

Both can be specified in the host connection string, keeping in mind that the '@' in the principal name must be encoded as "%40":

    my $mc = MongoDB::MongoClient->new(
        host =>

The default service name is 'mongodb'. It can be changed with the auth_mechanism_properties attribute or in the connection string.

    auth_mechanism_properties => { SERVICE_NAME => 'other_service' }



You MUST call the "reconnect" method on any MongoDB::MongoClient objects after forking or spawning a thread.

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.


  • David Golden <>

  • Rassi <>

  • Mike Friedman <>

  • Kristina Chodorow <>

  • Florian Ragwitz <>


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

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004