NAME
MongoDB::MongoClient - A connection to a MongoDB server or multi-server deployment
VERSION
version v0.999.998.5
SYNOPSIS
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"
);
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.
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.
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.
ATTRIBUTES
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.
Defaults to the connection string URI mongodb://localhost:27017
.
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.
connect_type
Specifies the expected topology type of servers in the seed list. The default is 'none'.
Valid values include:
replicaSet – the topology is a replica set (ignore non replica set members during discovery)
direct – the topology is a single server (connect as if the server is a standlone, even if it looks like a replica set member)
none – discover the deployment topology by checking servers in the seed list and connect accordingly
timeout
Connection timeout in milliseconds. Defaults to 20000
.
query_timeout
# set query timeout to 1 second
my $client = MongoDB::MongoClient->new(query_timeout => 1000);
# set query timeout to 6 seconds
$client->query_timeout(6000);
This will cause all queries (including find_one
s and run_command
s) 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
ssl
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 => 'default'
. You can use the scheme 'none' to disable this check.
Disabling certificate or hostname verification is a security risk and is not recommended.
w
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 callgetLastError
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: http://www.mongodb.org/display/DOCS/Data+Center+Awareness
wtimeout
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.
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.
server_selection_timeout_ms
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.
local_threshold_ms
The width of the 'latency window': when choosing between multiple suitable servers for an operation, the acceptable delta in milliseconds 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.
read_preference
A MongoDB::ReadPreference object, or a hash reference of attributes to construct such an object. The default is mode 'primary'.
For core documentation on read preference see http://docs.mongodb.org/manual/core/read-preference/.
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
.
heartbeat_frequency_ms
The time in milliseconds between scans of all servers to check if they are up and update their latency. Defaults to 60,000 ms.
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.
password
If an "auth_mechanism" requires a password, this attribute will be used. Otherwise, it will be ignored.
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".
auth_mechanism
This attribute determines how the client authenticates with the server. Valid values are:
NONE
DEFAULT
MONGODB-CR
MONGODB-X509
GSSAPI
PLAIN
SCRAM-SHA-1
If not specified, then if no username is provided, it defaults to NONE. If a username is provided, it is set to DEFAULT, which chooses SCRAM-SHA-1 if available or MONGODB-CR otherwise.
auth_mechanism_properties
This is an optional hash reference of authentication mechanism specific properties. See "AUTHENTICATION" for details.
dt_type
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.
inflate_dbrefs
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.
inflate_regexps
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.
auto_connect (DEPRECATED)
This attribute no longer has any effect. Connections always connect on demand.
auto_reconnect (DEPRECATED)
This attribute no longer has any effect. Connections always reconnect on demand.
find_master (DEPRECATED)
This attribute no longer has any effect. The driver will always attempt to find an appropriate server for every operation.
sasl (DEPRECATED)
If true, the driver will set the authentication mechanism based on the sasl_mechanism
property.
sasl_mechanism (DEPRECATED)
This specifies the SASL mechanism to use for authentication with a MongoDB server. It has the same valid values as "auth_mechanism". The default is GSSAPI.
METHODS
connect
$client->connect;
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.
disconnect
$client->disconnect;
Drops all connections to servers.
database_names
my @dbs = $client->database_names;
Lists all databases on the MongoDB server.
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 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});
fsync_unlock
$conn->fsync_unlock();
Unlocks a database server to allow writes and reverses the operation of a $conn->fsync({lock => 1}); operation.
authenticate (DEPRECATED)
$client->authenticate($dbname, $username, $password, $is_digest);
This legacy method is deprecated but kept for backwards compatibility.
Instead, authentication credentials should be provided as constructor arguments or as part of the connection URI.
When authenticate
is called, it disconnects the client (if any connections had been made), sets client attributes as if the username and password had been used initially in the client constructor, and reconnects to the configured servers. The authentication mechanism will be MONGO-CR for servers before version 3.0 and SCRAM-SHA-1 for 3.0 or later.
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 proper hashing yourself.
See also the "AUTHENTICATION" section.
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
MongoDB uses a pseudo-URI connection string to specify one or more servers to connect to, along with configuration options.
To connect to more than one database server, provide host or host:port pairs as a comma separated list:
mongodb://host1[:port1][,host2[:port2],...[,hostN[:portN]]]
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.
If a single, non-replica-set server is found, or if the "connect_type" (or connect
URI option) is 'direct', the deployment is treated as a single server deployment. For a replica set member, forcing the connection type to be 'direct' routes all operations to it alone; this is useful for carrying out administrative activities on that server.
The connection string may also have a username and password:
mongodb://username:password@host1:port1,host2:port2
The username and password must be URL-escaped.
A optional database name for authentication may be given:
mongodb://username:password@host1:port1,host2:port2/my_database
Finally, connection string options may 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
The currently supported connection string options are:
*authMechanism *authMechanism.SERVICE_NAME *connect *connectTimeoutMS *journal *readPreference *readPreferenceTags *ssl *w *wtimeoutMS
See the official MongoDB documentation on connection strings for more on the URI format and connection string options: http://docs.mongodb.org/manual/reference/connection-string/.
SERVER SELECTION
For a single server deployment or a direct connection to a mongod or mongos, all reads and writes and 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), 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 default 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 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 server is not immediately available, the driver will block for up to "server_selection_timeout_ms" milliseconds waiting for a suitable server to become available. If no server is available at the end of that time, an exception is thrown.
SERVER MONITORING
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 an server operation fails because of a "not master" or "node is recovering" error, the server is flagged as unavailable. Assuming the error is caught and handled, the next operation will rescan all servers immediately to find a new primary.
Whenever a server is found to be unavailable, the driver records this fact, but can continue to function as long as other servers are suitable per "SERVER SELECTION".
AUTHENTICATION
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:
MONGODB-CR -- legacy username-password challenge-response
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: http://docs.mongodb.org/manual/core/access-control/.
Usage information for each mechanism is given below.
MONGODB-CR and SCRAM-SHA-1 (for username/password)
These mechnisms 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://mongo.example.com/",
username => "johndoe",
password => "trustno1",
);
my $mc = MongoDB::MongoClient->new(
host => "mongodb://johndoe:trustno1@mongo.example.com/",
);
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 definedin 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://johndoe:trustno1@mongo.example.com/auth_db
MONGODB-X509 (for SSL client certificate)
X509 authentication requires SSL support (IO::Socket::SSL) and requires that a client certificate be configured and that the username attribute be set to the "Subject" field, formatted according to RFC 2253. To find the correct username, run the openssl
program as follows:
$ openssl x509 -in certs/client.pem -inform PEM -subject -nameopt RFC2253
subject= CN=XXXXXXXXXXX,OU=XXXXXXXX,O=XXXXXXX,ST=XXXXXXXXXX,C=XX
In this case the username
attribute would be CN=XXXXXXXXXXX,OU=XXXXXXXX,O=XXXXXXX,ST=XXXXXXXXXX,C=XX
.
Configure your client with the correct username and ssl parameters, and specify the "MONGODB-X509" authentication mechanism.
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",
username => "CN=XXXXXXXXXXX,OU=XXXXXXXX,O=XXXXXXX,ST=XXXXXXXXXX,C=XX"
);
PLAIN (for LDAP)
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://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 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 CPAM 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://mongo.example.com',
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 =>
'mongodb://johndoe%40EXAMPLE.COM@mongo.examplecom/?authMechanism=GSSAPI',
);
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' }
mongodb://.../?authMechanism=GSSAPI&authMechanism.SERVICE_NAME=other_service
THREAD-SAFETY AND FORK-SAFETY
Existing connections to servers are closed after forking or spawning a thread. They will reconnect on demand.
AUTHORS
David Golden <david@mongodb.com>
Mike Friedman <friedo@mongodb.com>
Kristina Chodorow <kristina@mongodb.com>
Florian Ragwitz <rafl@debian.org>
COPYRIGHT AND LICENSE
This software is Copyright (c) 2015 by MongoDB, Inc..
This is free software, licensed under:
The Apache License, Version 2.0, January 2004