MongoDB::MongoClient - A connection to a MongoDB server


version v0.704.1.0


    use strict;
    use warnings;
    use MongoDB;

    # connects to localhost:27017
    my $client = MongoDB::MongoClient->new;

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


The MongoDB::MongoClient class creates 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" section 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. If you would like to learn more about authentication, see the authenticate method.

Connecting is relatively expensive, so try not to open superfluous connections.

There is no way to explicitly disconnect from the database. However, the connection will automatically be closed and cleaned up when no references to the MongoDB::MongoClient object exist, which occurs when $client goes out of scope (or earlier if you undefine it with undef).



Server or servers to connect to. Defaults to mongodb://localhost:27017.

To connect to more than one database server, use the format:


An arbitrary number of hosts can be specified.

The connect method will return success if it can connect to at least one of the hosts listed. If it cannot connect to any hosts, it will die.

If a port is not specified for a given host, it will default to 27017. For example, to connecting to localhost:27017 and localhost:27018:

    my $client = MongoDB::MongoClient->new("host" => "mongodb://localhost,localhost:27018");

This will succeed if either localhost:27017 or localhost:27018 are available.

The connect method will also try to determine who is the primary if more than one server is given. It will try the hosts in order from left to right. As soon as one of the hosts reports that it is the primary, the connect will return success. If no hosts report themselves as a primary, the connect will die.

If username and password are given, success is conditional on being able to log into the database as well as connect. By default, the driver will attempt to authenticate with the admin database. If a different database is specified using the db_name property, it will be used instead.


The client write concern.

  • -1 Errors ignored. Do not use this.

  • 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. You must call getLastError manually to check if a request succeeds. This option is not recommended.

  • 1 Acknowledged. This is the default. 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.

In MongoDB v2.0+, you can "tag" replica members. With "tagging" you can specify a new "getLastErrorMode" where you can create new rules on how your data is replicated. To used you getLastErrorMode, you pass in the name of the mode to the w parameter. For more information see:


The number of milliseconds an operation should wait for w slaves to replicate it.

Defaults to 1000 (1 second).

See w above for more information.


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.


Boolean indicating whether or not to reconnect if the connection is interrupted. Defaults to 1.


Boolean indication whether or not to connect automatically on object construction. Defaults to 1.


Connection timeout in milliseconds. Defaults to 20000.


Username for this client connection. Optional. If this and the password field are set, the client will attempt to authenticate on connection/reconnection.


Password for this connection. Optional. If this and the username field are set, the client will attempt to authenticate on connection/reconnection.


Database to authenticate on for this connection. Optional. If this, the username, and the password fields are set, the client will attempt to authenticate against this database on connection/reconnection. Defaults to "admin".


    # set query timeout to 1 second
    my $client = MongoDB::MongoClient->new(query_timeout => 1000);

    # set query timeout to 6 seconds

This will cause all queries (including find_ones and run_commands) to die after this period if the database has not responded.

This value is in milliseconds and defaults to the value of "timeout" in MongoDB::Cursor.

    $MongoDB::Cursor::timeout = 5000;
    # query timeout for $conn will be 5 seconds
    my $client = MongoDB::MongoClient->new;

A value of -1 will cause the driver to wait forever for responses and 0 will cause it to die immediately.

This value overrides "timeout" in MongoDB::Cursor.

    $MongoDB::Cursor::timeout = 1000;
    my $client = MongoDB::MongoClient->new(query_timeout => 10);
    # timeout for $conn is 10 milliseconds


This is the largest document, in bytes, storable by MongoDB. The driver queries MongoDB on connection to determine this value. It defaults to 4MB.


If this is true, the driver will attempt to find a primary given the list of hosts. The primary-finding algorithm looks like:

    for host in hosts

        if host is the primary
             return host

        else if host is a replica set member
            primary := replica set's primary
            return primary

If no primary is found, the connection will fail.

If this is not set (or set to the default, 0), the driver will simply use the first host in the host list for all connections. This can be useful for directly connecting to secondaries for reads.

If you are connecting to a secondary, you should read "slave_okay" in MongoDB::Cursor.

You can use the ismaster command to find the members of a replica set:

    my $result = $db->run_command({ismaster => 1});

The primary and secondary hosts are listed in the hosts field, the slaves are in the passives field, and arbiters are in the arbiters field.


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

This option will be ignored if the driver was not compiled with the SSL flag. You must also be using a database server that supports SSL.

The driver must be built as follows for SSL support:

    perl Makefile.PL --ssl
    make install

Alternatively, you can set the PERL_MONGODB_WITH_SSL environment variable before installing:


The libcrypto and libssl libraries are required for SSL support.


This attribute is experimental.

If set to 1, the driver will attempt to negotiate SASL authentication upon connection. See "sasl_mechanism" for a list of the currently supported mechanisms. The driver must be built as follows for SASL support:

    perl Makefile.PL --sasl
    make install

Alternatively, you can set the PERL_MONGODB_WITH_SASL environment variable before installing:


The libgsasl library is required for SASL support. RedHat/CentOS users can find it in the EPEL repositories.

Future versions of this driver may switch to Cyrus SASL in order to be consistent with the MongoDB server, which now uses Cyrus.


This attribute is experimental.

This specifies the SASL mechanism to use for authentication with a MongoDB server. (See "sasl".) The default is GSSAPI. The supported SASL mechanisms are:

  • GSSAPI. This is the default. GSSAPI will attempt to authenticate against Kerberos for MongoDB Enterprise 2.4+. You must run your program from within a kinit session and set the username attribute to the Kerberos principal name, e.g. user@EXAMPLE.COM.

  • PLAIN. The SASL PLAIN mechanism will attempt to authenticate against LDAP for MongoDB Enterprise 2.6+. Because the password is not encrypted, you should only use this mechanism over a secure connection. You must set the username and password attributes to your LDAP credentials.


Sets the type of object which is returned for DateTime fields. The default is DateTime. Other acceptable values are DateTime::Tiny and undef. The latter will give you the raw epoch value rather than an object.


Controls whether DBRefs are automatically inflated into MongoDB::DBRef objects. Defaults to true. Set this to 0 if you don't want to auto-inflate them.


Controls whether regular expressions stored in MongoDB are inflated into MongoDB::BSON::Regexp objects instead of native Perl Regexps. The default is false. This can be dangerous, since the JavaScript regexps used internally by MongoDB are of a different dialect than Perl's. The default for this attribute may become true in future versions of the driver.




Connects to the MongoDB server. Called automatically on object construction if "auto_connect" is true.


    my @dbs = $client->database_names;

Lists all databases on the MongoDB server.


    my $database = $client->get_database('foo');

Returns a MongoDB::Database instance for the database with the given $name.


    $master = $client->get_master

Determines which host of a paired connection is master. Does nothing for a non-paired connection. This need never be invoked by a user, it is called automatically by internal functions. Returns the index of the master connection in the list of connections or -1 if it cannot be determined.

authenticate ($dbname, $username, $password, $is_digest?)

    $client->authenticate('foo', 'username', 'secret');

Attempts to authenticate for use of the $dbname database with $username and $password. Passwords are expected to be cleartext and will be automatically hashed before sending over the wire, unless $is_digest is true, which will assume you already did the hashing on yourself.

See also the core documentation on authentication:


    my ($insert, $ids) = MongoDB::write_insert('', [{name => "joe", age => 40}]);

Low-level function to send a string directly to the database. Use MongoDB::write_insert, MongoDB::write_update, MongoDB::write_remove, or MongoDB::write_query to create a valid string.


    my $ok = $client->recv($cursor);

Low-level function to receive a response from the database into a cursor. Dies on error. Returns true if any results were received and false otherwise.



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.


    $conn->read_preference(MongoDB::MongoClient->PRIMARY_PREFERRED, [{'disk' => 'ssd'}, {'rack' => 'k'}]);

Sets the read preference for this connection. The first argument is the read preference mode and should be one of four constants: PRIMARY, SECONDARY, PRIMARY_PREFERRED, or SECONDARY_PREFERRED (NEAREST is not yet supported). In order to use read preference, "find_master" in MongoDB::MongoClient must be set. The second argument (optional) is an array reference containing tagsets. The tagsets can be used to match the tags for replica set secondaries. See also "read_preference" in MongoDB::Cursor. For core documentation on read preference see



Chooses a replica set member to which this connection should route read operations, according to the read preference that has been set via "read_preference" in MongoDB::MongoClient or "read_preference" in MongoDB::Cursor. This method is called automatically when the read preference or replica set state changes, and generally does not need to be called by application code.



If it has been at least 5 seconds since last checking replica set state, then ping all replica set members. Calls "repin" in MongoDB::MongoClient if a previously reachable node is now unreachable, or a previously unreachable node is now reachable. This method is called automatically before communicating with the server, and therefore should not generally be called by client code.


Existing connections are closed when a thread is created. If auto_reconnect is true, then connections will be re-established as needed.


Core documentation on connections:


  • David Golden <>

  • Mike Friedman <>

  • Kristina Chodorow <>

  • Florian Ragwitz <>


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

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004