Provided by: libmongodb-perl_1.8.1-1_amd64
NAME
MongoDB::MongoClient - A connection to a MongoDB server or multi-server deployment
VERSION
version v1.8.1
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" ); # 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. 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 <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. 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". 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. 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. 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 MongoDB::BSON. It may be initialized with a hash reference that will be coerced into a new MongoDB::BSON object. If not provided, one will be generated as follows: MongoDB::BSON->new( dbref_callback => sub { return MongoDB::DBRef->new(shift) }, dt_type => $client->dt_type, prefer_numeric => $MongoDB::BSON::looks_like_number || 0, ( $MongoDB::BSON::char ne '$' ? ( op_char => $MongoDB::BSON::char ) : () ), ); This will inflate all DBRefs to MongoDB::DBRef objects, set "dt_type" based on the client's "db_type" accessor, and set the "prefer_numeric" and "op_char" attributes based on the deprecated legacy global variables. 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 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. 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_pref_mode 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 <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. 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 <http://docs.mongodb.org/manual/core/read-preference/>. 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. replica_set_name 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. 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. This may be set in a connection string with the "serverSelectionTimeoutMS" option. server_selection_try_once 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. socket_check_interval_ms 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. socket_timeout_ms 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. 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 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. (A future version of the driver may support customizing ssl via the connection string.) 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. 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. w 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. 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 custom write concern For more information see Data Center Awareness <http://docs.mongodb.org/manual/data-center-awareness/> This may be set 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). See "w" above for more information. This may be set in a connection string with the "wTimeoutMS" option. 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 the "readConcernLevel" option. dt_type (DEPRECATED AND READ-ONLY) Sets the type of object which is returned for DateTime fields. The default is DateTime. Other acceptable values are DateTime::Tiny, Time::Moment and "undef". The latter will give you the raw epoch value (possibly as a floating point value) rather than an object. This will be used to construct "bson_codec" object if one is not provided. As this has a one-time effect, it is now read-only to help you detect code that was trying to change after the fact during program execution. For temporary or localized changes, look into overriding the "bson_codec" object for a database or collection object. query_timeout (DEPRECATED AND READ-ONLY) # set query timeout to 1 second my $client = MongoDB::MongoClient->new(query_timeout => 1000); This option has been renamed as "socket_timeout_ms". If this option is set and that one is not, this will be used. This value is in milliseconds and defaults to 30000. 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. timeout (DEPRECATED AND READ-ONLY) This option has been renamed as "connect_timeout_ms". If this option is set and that one is not, this will be used. Connection timeout is in milliseconds. Defaults to 10000.
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. 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", the type will be 'Single' if there is only one server in the list of hosts, and 'Sharded' if there are more than one. N.B. A single mongos will have a topology type of 'Single', as that mongos will be used for all reads and writes, just like a standalone mongod. The 'Sharded' type indicates a sharded cluster with multiple mongos servers, and reads/writes will be distributed acc 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. 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. 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. 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.
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. 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: 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: *appName *authMechanism *authMechanism.SERVICE_NAME *connectTimeoutMS *journal *readPreference *readPreferenceTags *replicaSet *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 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 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.
SERVER MONITORING AND FAILOVER
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.
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 <http://tools.ietf.org/html/rfc5802>. 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), 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://sslmongo.example.com/", ssl => { SSL_ca_file => "certs/ca.pem", SSL_cert_file => "certs/client.pem", }, auth_mechanism => "MONGODB-X509", ); 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 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://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&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.
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) 2018 by MongoDB, Inc. This is free software, licensed under: The Apache License, Version 2.0, January 2004