1MongoDB::MongoClient(3)User Contributed Perl DocumentatioMnongoDB::MongoClient(3)
2
3
4

NAME

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

VERSION

10       version v2.0.3
11

SYNOPSIS

13           use MongoDB; # also loads MongoDB::MongoClient
14
15           # connect to localhost:27017
16           my $client = MongoDB::MongoClient->new;
17
18           # connect to specific host and port
19           my $client = MongoDB::MongoClient->new(
20               host => "mongodb://mongo.example.com:27017"
21           );
22
23           # connect to a replica set (set name *required*)
24           my $client = MongoDB::MongoClient->new(
25               host => "mongodb://mongo1.example.com,mongo2.example.com",
26               replica_set_name => 'myset',
27           );
28
29           # connect to a replica set with URI (set name *required*)
30           my $client = MongoDB::MongoClient->new(
31               host => "mongodb://mongo1.example.com,mongo2.example.com/?replicaSet=myset",
32           );
33
34           my $db = $client->get_database("test");
35           my $coll = $db->get_collection("people");
36
37           $coll->insert({ name => "John Doe", age => 42 });
38           my @people = $coll->find()->all();
39

DESCRIPTION

41       The "MongoDB::MongoClient" class represents a client connection to one
42       or more MongoDB servers.
43
44       By default, it connects to a single server running on the local machine
45       listening on the default port 27017:
46
47           # connects to localhost:27017
48           my $client = MongoDB::MongoClient->new;
49
50       It can connect to a database server running anywhere, though:
51
52           my $client = MongoDB::MongoClient->new(host => 'example.com:12345');
53
54       See the "host" attribute for more options for connecting to MongoDB.
55
56       MongoDB can be started in authentication mode
57       <http://docs.mongodb.org/manual/core/authentication/>, which requires
58       clients to log in before manipulating data.  By default, MongoDB does
59       not start in this mode, so no username or password is required to make
60       a fully functional connection.  To configure the client for
61       authentication, see the "AUTHENTICATION" section.
62
63       The actual socket connections are lazy and created on demand.  When the
64       client object goes out of scope, all socket will be closed.  Note that
65       MongoDB::Database, MongoDB::Collection and related classes could hold a
66       reference to the client as well.  Only when all references are out of
67       scope will the sockets be closed.
68

ATTRIBUTES

70   host
71       The "host" attribute specifies either a single server to connect to (as
72       "hostname" or "hostname:port"), or else a connection string URI with a
73       seed list of one or more servers plus connection options.
74
75       Defaults to the connection string URI "mongodb://localhost:27017".
76
77       For IPv6 support, you must have a recent version of IO::Socket::IP
78       installed.  This module ships with the Perl core since v5.20.0 and is
79       available on CPAN for older Perls.
80
81   app_name
82       This attribute specifies an application name that should be associated
83       with this client.  The application name will be communicated to the
84       server as part of the initial connection handshake, and will appear in
85       connection-level and operation-level diagnostics on the server
86       generated on behalf of this client.  This may be set in a connection
87       string with the "appName" option.
88
89       The default is the empty string, which indicates a lack of an
90       application name.
91
92       The application name must not exceed 128 bytes.
93
94   auth_mechanism
95       This attribute determines how the client authenticates with the server.
96       Valid values are:
97
98       ·   NONE
99
100       ·   DEFAULT
101
102       ·   MONGODB-CR
103
104       ·   MONGODB-X509
105
106       ·   GSSAPI
107
108       ·   PLAIN
109
110       ·   SCRAM-SHA-1
111
112       If not specified, then if no username is provided, it defaults to NONE.
113       If a username is provided, it is set to DEFAULT, which chooses
114       SCRAM-SHA-1 if available or MONGODB-CR otherwise.
115
116       This may be set in a connection string with the "authMechanism" option.
117
118   auth_mechanism_properties
119       This is an optional hash reference of authentication mechanism specific
120       properties.  See "AUTHENTICATION" for details.
121
122       This may be set in a connection string with the
123       "authMechanismProperties" option.  If given, the value must be
124       key/value pairs joined with a ":".  Multiple pairs must be separated by
125       a comma.  If ": or "," appear in a key or value, they must be URL
126       encoded.
127
128   bson_codec
129       An object that provides the "encode_one" and "decode_one" methods, such
130       as from BSON.  It may be initialized with a hash reference that will be
131       coerced into a new BSON object.
132
133       If not provided, a BSON object with default values will be generated.
134
135   compressors
136       An array reference of compression type names. Currently only "zlib" is
137       supported.
138
139   zlib_compression_level
140       An integer from "-1" to 9 specifying the compression level to use when
141       "compression" is set to "zlib".
142
143       Note: When the special value "-1" is given, the default compression
144       level will be used.
145
146   connect_timeout_ms
147       This attribute specifies the amount of time in milliseconds to wait for
148       a new connection to a server.
149
150       The default is 10,000 ms.
151
152       If set to a negative value, connection operations will block
153       indefinitely until the server replies or until the operating system
154       TCP/IP stack gives up (e.g. if the name can't resolve or there is no
155       process listening on the target host/port).
156
157       A zero value polls the socket during connection and is thus likely to
158       fail except when talking to a local process (and perhaps even then).
159
160       This may be set in a connection string with the "connectTimeoutMS"
161       option.
162
163   db_name
164       Optional.  If an "auth_mechanism" requires a database for
165       authentication, this attribute will be used.  Otherwise, it will be
166       ignored. Defaults to "admin".
167
168       This may be provided in the connection string URI as a path between the
169       authority and option parameter sections.  For example, to authenticate
170       against the "admin" database (showing a configuration option only for
171       illustration):
172
173           mongodb://localhost/admin?readPreference=primary
174
175   heartbeat_frequency_ms
176       The time in milliseconds (non-negative) between scans of all servers to
177       check if they are up and update their latency.  Defaults to 60,000 ms.
178
179       This may be set in a connection string with the "heartbeatFrequencyMS"
180       option.
181
182   j
183       If true, the client will block until write operations have been
184       committed to the server's journal. Prior to MongoDB 2.6, this option
185       was ignored if the server was running without journaling. Starting with
186       MongoDB 2.6, write operations will fail if this option is used when the
187       server is running without journaling.
188
189       This may be set in a connection string with the "journal" option as the
190       strings 'true' or 'false'.
191
192   local_threshold_ms
193       The width of the 'latency window': when choosing between multiple
194       suitable servers for an operation, the acceptable delta in milliseconds
195       (non-negative) between shortest and longest average round-trip times.
196       Servers within the latency window are selected randomly.
197
198       Set this to "0" to always select the server with the shortest average
199       round trip time.  Set this to a very high value to always randomly
200       choose any known server.
201
202       Defaults to 15 ms.
203
204       See "SERVER SELECTION" for more details.
205
206       This may be set in a connection string with the "localThresholdMS"
207       option.
208
209   max_staleness_seconds
210       The "max_staleness_seconds" parameter represents the maximum
211       replication lag in seconds (wall clock time) that a secondary can
212       suffer and still be eligible for reads. The default is -1, which
213       disables staleness checks.  Otherwise, it must be a positive integer.
214
215       Note: this will only be used for server versions 3.4 or greater, as
216       that was when support for staleness tracking was added.
217
218       If the read preference mode is 'primary', then "max_staleness_seconds"
219       must not be supplied.
220
221       The "max_staleness_seconds" must be at least the
222       "heartbeat_frequency_ms" plus 10 seconds (which is how often the server
223       makes idle writes to the oplog).
224
225       This may be set in a connection string with the "maxStalenessSeconds"
226       option.
227
228   max_time_ms
229       Specifies the maximum amount of time in (non-negative) milliseconds
230       that the server should use for working on a database command.  Defaults
231       to 0, which disables this feature.  Make sure this value is shorter
232       than "socket_timeout_ms".
233
234       Note: this will only be used for server versions 2.6 or greater, as
235       that was when the $maxTimeMS meta-operator was introduced.
236
237       You are strongly encouraged to set this variable if you know your
238       environment has MongoDB 2.6 or later, as getting a definitive error
239       response from the server is vastly preferred over a getting a network
240       socket timeout.
241
242       This may be set in a connection string with the "maxTimeMS" option.
243
244   monitoring_callback
245       Specifies a code reference used to receive monitoring events.  See
246       MongoDB::Monitoring for more details.
247
248   password
249       If an "auth_mechanism" requires a password, this attribute will be
250       used.  Otherwise, it will be ignored.
251
252       This may be provided in the connection string URI as a
253       "username:password" pair in the leading portion of the authority
254       section before a "@" character.  For example, to authenticate as user
255       "mulder" with password "trustno1":
256
257           mongodb://mulder:trustno1@localhost
258
259       If the username or password have a ":" or "@" in it, they must be URL
260       encoded.  An empty password still requires a ":" character.
261
262   port
263       If a network port is not specified as part of the "host" attribute,
264       this attribute provides the port to use.  It defaults to 27107.
265
266   read_pref_mode
267       The read preference mode determines which server types are candidates
268       for a read operation.  Valid values are:
269
270       ·   primary
271
272       ·   primaryPreferred
273
274       ·   secondary
275
276       ·   secondaryPreferred
277
278       ·   nearest
279
280       For core documentation on read preference see
281       <http://docs.mongodb.org/manual/core/read-preference/>.
282
283       This may be set in a connection string with the "readPreference"
284       option.
285
286   read_pref_tag_sets
287       The "read_pref_tag_sets" parameter is an ordered list of tag sets used
288       to restrict the eligibility of servers, such as for data center
289       awareness.  It must be an array reference of hash references.
290
291       The application of "read_pref_tag_sets" varies depending on the
292       "read_pref_mode" parameter.  If the "read_pref_mode" is 'primary', then
293       "read_pref_tag_sets" must not be supplied.
294
295       For core documentation on read preference see
296       <http://docs.mongodb.org/manual/core/read-preference/>.
297
298       This may be set in a connection string with the "readPreferenceTags"
299       option.  If given, the value must be key/value pairs joined with a ":".
300       Multiple pairs must be separated by a comma.  If ": or "," appear in a
301       key or value, they must be URL encoded.  The "readPreferenceTags"
302       option may appear more than once, in which case each document will be
303       added to the tag set list.
304
305   replica_set_name
306       Specifies the replica set name to connect to.  If this string is non-
307       empty, then the topology is treated as a replica set and all server
308       replica set names must match this or they will be removed from the
309       topology.
310
311       This may be set in a connection string with the "replicaSet" option.
312
313   server_selection_timeout_ms
314       This attribute specifies the amount of time in milliseconds to wait for
315       a suitable server to be available for a read or write operation.  If no
316       server is available within this time period, an exception will be
317       thrown.
318
319       The default is 30,000 ms.
320
321       See "SERVER SELECTION" for more details.
322
323       This may be set in a connection string with the
324       "serverSelectionTimeoutMS" option.
325
326   server_selection_try_once
327       This attribute controls whether the client will make only a single
328       attempt to find a suitable server for a read or write operation.  The
329       default is true.
330
331       When true, the client will not use the "server_selection_timeout_ms".
332       Instead, if the topology information is stale and needs to be checked
333       or if no suitable server is available, the client will make a single
334       scan of all known servers to try to find a suitable one.
335
336       When false, the client will continually scan known servers until a
337       suitable server is found or the "serverSelectionTimeoutMS" is reached.
338
339       See "SERVER SELECTION" for more details.
340
341       This may be set in a connection string with the
342       "serverSelectionTryOnce" option.
343
344   socket_check_interval_ms
345       If a socket to a server has not been used in this many milliseconds, an
346       "ismaster" command will be issued to check the status of the server
347       before issuing any reads or writes. Must be non-negative.
348
349       The default is 5,000 ms.
350
351       This may be set in a connection string with the "socketCheckIntervalMS"
352       option.
353
354   socket_timeout_ms
355       This attribute specifies the amount of time in milliseconds to wait for
356       a reply from the server before issuing a network exception.
357
358       The default is 30,000 ms.
359
360       If set to a negative value, socket operations will block indefinitely
361       until the server replies or until the operating system TCP/IP stack
362       gives up.
363
364       A zero value polls the socket for available data and is thus likely to
365       fail except when talking to a local process (and perhaps even then).
366
367       This may be set in a connection string with the "socketTimeoutMS"
368       option.
369
370   ssl
371           ssl => 1
372           ssl => \%ssl_options
373
374       This tells the driver that you are connecting to an SSL mongodb
375       instance.
376
377       You must have IO::Socket::SSL 1.42+ and Net::SSLeay 1.49+ installed for
378       SSL support.
379
380       The "ssl" attribute takes either a boolean value or a hash reference of
381       options to pass to IO::Socket::SSL.  For example, to set a CA file to
382       validate the server certificate and set a client certificate for the
383       server to validate, you could set the attribute like this:
384
385           ssl => {
386               SSL_ca_file   => "/path/to/ca.pem",
387               SSL_cert_file => "/path/to/client.pem",
388           }
389
390       If "SSL_ca_file" is not provided, server certificates are verified
391       against a default list of CAs, either Mozilla::CA or an operating-
392       system-specific default CA file.  To disable verification, you can use
393       "SSL_verify_mode => 0x00".
394
395       You are strongly encouraged to use your own CA file for increased
396       security.
397
398       Server hostnames are also validated against the CN name in the server
399       certificate using "SSL_verifycn_scheme => 'http'".  You can use the
400       scheme 'none' to disable this check.
401
402       Disabling certificate or hostname verification is a security risk and
403       is not recommended.
404
405       This may be set to the string 'true' or 'false' in a connection string
406       with the "ssl" option, which will enable ssl with default
407       configuration.  (A future version of the driver may support customizing
408       ssl via the connection string.)
409
410   username
411       Optional username for this client connection.  If this field is set,
412       the client will attempt to authenticate when connecting to servers.
413       Depending on the "auth_mechanism", the "password" field or other
414       attributes will need to be set for authentication to succeed.
415
416       This may be provided in the connection string URI as a
417       "username:password" pair in the leading portion of the authority
418       section before a "@" character.  For example, to authenticate as user
419       "mulder" with password "trustno1":
420
421           mongodb://mulder:trustno1@localhost
422
423       If the username or password have a ":" or "@" in it, they must be URL
424       encoded.  An empty password still requires a ":" character.
425
426   w
427       The client write concern.
428
429       ·   0 Unacknowledged. MongoClient will NOT wait for an acknowledgment
430           that the server has received and processed the request. Older
431           documentation may refer to this as "fire-and-forget" mode.  This
432           option is not recommended.
433
434       ·   1 Acknowledged. This is the default. MongoClient will wait until
435           the primary MongoDB acknowledges the write.
436
437       ·   2 Replica acknowledged. MongoClient will wait until at least two
438           replicas (primary and one secondary) acknowledge the write. You can
439           set a higher number for more replicas.
440
441       ·   "all" All replicas acknowledged.
442
443       ·   "majority" A majority of replicas acknowledged.
444
445       In MongoDB v2.0+, you can "tag" replica members. With "tagging" you can
446       specify a custom write concern For more information see Data Center
447       Awareness <http://docs.mongodb.org/manual/data-center-awareness/>
448
449       This may be set in a connection string with the "w" option.
450
451   wtimeout
452       The number of milliseconds an operation should wait for "w" secondaries
453       to replicate it.
454
455       Defaults to 1000 (1 second).
456
457       See "w" above for more information.
458
459       This may be set in a connection string with the "wTimeoutMS" option.
460
461   read_concern_level
462       The read concern level determines the consistency level required of
463       data being read.
464
465       The default level is "undef", which means the server will use its
466       configured default.
467
468       If the level is set to "local", reads will return the latest data a
469       server has locally.
470
471       Additional levels are storage engine specific.  See Read Concern
472       <http://docs.mongodb.org/manual/search/?query=readConcern> in the
473       MongoDB documentation for more details.
474
475       This may be set in a connection string with the the "readConcernLevel"
476       option.
477
478   retry_writes
479       Whether the client should use retryable writes for supported commands.
480       The default value is false, which means that no write commands will be
481       retried.
482
483       If this is set to a true value, then commands which support retryable
484       writes will be retried on certain errors, such as "not master" and
485       "node is recovering" errors.
486
487       This may be set in a connection string with the "retryWrites" option.
488
489       Note that this is only supported on MongoDB > 3.6 in Replica Set or
490       Shard Clusters, and will be ignored on other deployments.
491
492       Unacknowledged write operations also do not support retryable writes,
493       even when retry_writes has been enabled.
494
495       The supported single statement write operations are currently as
496       follows:
497
498       ·   "insert_one"
499
500       ·   "update_one"
501
502       ·   "replace_one"
503
504       ·   "delete_one"
505
506       ·   "find_one_and_delete"
507
508       ·   "find_one_and_replace"
509
510       ·   "find_one_and_update"
511
512       The supported multi statement write operations are as follows:
513
514       ·   "insert_many"
515
516       ·   "bulk_write"
517
518       The multi statement operations may be ether ordered or unordered. Note
519       that for "bulk_write" operations, the request may not include
520       update_many or delete_many operations.
521

METHODS

523   read_preference
524       Returns a MongoDB::ReadPreference object constructed from
525       "read_pref_mode" and "read_pref_tag_sets"
526
527       The use of "read_preference" as a mutator has been removed.  Read
528       preference is read-only.  If you need a different read preference for a
529       database or collection, you can specify that in "get_database" or
530       "get_collection".
531
532   write_concern
533       Returns a MongoDB::WriteConcern object constructed from "w",
534       "write_concern" and "j".
535
536   read_concern
537       Returns a MongoDB::ReadConcern object constructed from
538       "read_concern_level".
539
540   topology_type
541       Returns an enumerated topology type.  If the "replica_set_name" is set,
542       the value will be either 'ReplicaSetWithPrimary' or
543       'ReplicaSetNoPrimary' (if the primary is down or not yet discovered).
544       Without "replica_set_name", if there is more than one server in the
545       list of hosts, the type will be 'Sharded'.
546
547       With only a single host and no replica set name, the topology type will
548       start as 'Direct' until the server is contacted the first time, after
549       which the type will be 'Sharded' for a mongos or 'Single' for
550       standalone server or direct connection to a replica set member.
551
552   connect
553           $client->connect;
554
555       Calling this method is unnecessary, as connections are established
556       automatically as needed.  It is kept for backwards compatibility.
557       Calling it will check all servers in the deployment which ensures a
558       connection to any that are available.
559
560       See "reconnect" for a method that is useful when using forks or
561       threads.
562
563   disconnect
564           $client->disconnect;
565
566       Drops all connections to servers.
567
568   reconnect
569           $client->reconnect;
570
571       This method closes all connections to the server, as if "disconnect"
572       were called, and then immediately reconnects.  It also clears the
573       session cache.  Use this after forking or spawning off a new thread.
574
575   topology_status
576           $client->topology_status;
577           $client->topology_status( refresh => 1 );
578
579       Returns a hash reference with server topology information like this:
580
581           {
582               'topology_type' => 'ReplicaSetWithPrimary'
583               'replica_set_name' => 'foo',
584               'last_scan_time'   => '1433766895.183241',
585               'servers'          => [
586                   {
587                       'address'     => 'localhost:50003',
588                       'ewma_rtt_ms' => '0.223462326',
589                       'type'        => 'RSSecondary'
590                   },
591                   {
592                       'address'     => 'localhost:50437',
593                       'ewma_rtt_ms' => '0.268435456',
594                       'type'        => 'RSArbiter'
595                   },
596                   {
597                       'address'     => 'localhost:50829',
598                       'ewma_rtt_ms' => '0.737782272',
599                       'type'        => 'RSPrimary'
600                   }
601               },
602           }
603
604       If the 'refresh' argument is true, then the topology will be scanned to
605       update server data before returning the hash reference.
606
607   start_session
608           $client->start_session;
609           $client->start_session( $options );
610
611       Returns a new MongoDB::ClientSession with the supplied options.
612
613       will throw a "MongoDB::ConfigurationError" if sessions are not
614       supported by the connected MongoDB deployment.
615
616       the options hash is an optional hash which can have the following keys:
617
618       ·   "causalConsistency" - Enable Causally Consistent reads for this
619           session. Defaults to true.
620
621       for more information see "options" in MongoDB::ClientSession.
622
623   list_databases
624           # get all information on all databases
625           my @dbs = $client->list_databases;
626
627           # get only the foo databases
628           my @foo_dbs = $client->list_databases({ filter => { name => qr/^foo/ } });
629
630       Lists all databases with information on each database. Supports
631       filtering by any of the output fields under the "filter" argument, such
632       as:
633
634       ·   "name"
635
636       ·   "sizeOnDisk"
637
638       ·   "empty"
639
640       ·   "shards"
641
642   database_names
643           my @dbs = $client->database_names;
644
645           # get only the foo database names
646           my @foo_dbs = $client->database_names({ filter => { name => qr/^foo/ } });
647
648       List of all database names on the MongoDB server. Supports filters in
649       the same way as "list_databases".
650
651   get_database, db
652           my $database = $client->get_database('foo');
653           my $database = $client->get_database('foo', $options);
654           my $database = $client->db('foo', $options);
655
656       Returns a MongoDB::Database instance for the database with the given
657       $name.
658
659       It takes an optional hash reference of options that are passed to the
660       MongoDB::Database constructor.
661
662       The "db" method is an alias for "get_database".
663
664   get_namespace, ns
665           my $collection = $client->get_namespace('test.foo');
666           my $collection = $client->get_namespace('test.foo', $options);
667           my $collection = $client->ns('test.foo', $options);
668
669       Returns a MongoDB::Collection instance for the given namespace.  The
670       namespace has both the database name and the collection name separated
671       with a dot character.
672
673       This is a quick way to get a collection object if you don't need the
674       database object separately.
675
676       It takes an optional hash reference of options that are passed to the
677       MongoDB::Collection constructor.  The intermediate MongoDB::Database
678       object will be created with default options.
679
680       The "ns" method is an alias for "get_namespace".
681
682   fsync(\%args)
683           $client->fsync();
684
685       A function that will forces the server to flush all pending writes to
686       the storage layer.
687
688       The fsync operation is synchronous by default, to run fsync
689       asynchronously, use the following form:
690
691           $client->fsync({async => 1});
692
693       The primary use of fsync is to lock the database during backup
694       operations. This will flush all data to the data storage layer and
695       block all write operations until you unlock the database. Note: you can
696       still read while the database is locked.
697
698           $conn->fsync({lock => 1});
699
700   fsync_unlock
701           $conn->fsync_unlock();
702
703       Unlocks a database server to allow writes and reverses the operation of
704       a $conn->fsync({lock => 1}); operation.
705
706   watch
707       Watches for changes on the cluster.
708
709       Perform an aggregation with an implicit initial $changeStream stage and
710       returns a MongoDB::ChangeStream result which can be used to iterate
711       over the changes in the cluster. This functionality is available since
712       MongoDB 4.0.
713
714           my $stream = $client->watch();
715           my $stream = $client->watch( \@pipeline );
716           my $stream = $client->watch( \@pipeline, \%options );
717
718           while (1) {
719
720               # This inner loop will only run until no more changes are
721               # available.
722               while (my $change = $stream->next) {
723                   # process $change
724               }
725           }
726
727       The returned stream will not block forever waiting for changes. If you
728       want to respond to changes over a longer time use "maxAwaitTimeMS" and
729       regularly call "next" in a loop.
730
731       See "watch" in MongoDB::Collection for details on usage and available
732       options.
733

DEPLOYMENT TOPOLOGY

735       MongoDB can operate as a single server or as a distributed system.  One
736       or more servers that collectively provide access to a single logical
737       set of MongoDB databases are referred to as a "deployment".
738
739       There are three types of deployments:
740
741       ·   Single server – a stand-alone mongod database
742
743       ·   Replica set – a set of mongod databases with data replication and
744           fail-over capability
745
746       ·   Sharded cluster – a distributed deployment that spreads data across
747           one or more shards, each of which can be a replica set.  Clients
748           communicate with a mongos process that routes operations to the
749           correct share.
750
751       The state of a deployment, including its type, which servers are
752       members, the server types of members and the round-trip network latency
753       to members is referred to as the "topology" of the deployment.
754
755       To the greatest extent possible, the MongoDB driver abstracts away the
756       details of communicating with different deployment types.  It
757       determines the deployment topology through a combination of the
758       connection string, configuration options and direct discovery
759       communicating with servers in the deployment.
760

CONNECTION STRING URI

762       MongoDB uses a pseudo-URI connection string to specify one or more
763       servers to connect to, along with configuration options.
764
765       NOTE: any non-printable ASCII characters should be UTF-8 encoded and
766       converted URL-escaped characters.
767
768       To connect to more than one database server, provide host or host:port
769       pairs as a comma separated list:
770
771           mongodb://host1[:port1][,host2[:port2],...[,hostN[:portN]]]
772
773       This list is referred to as the "seed list".  An arbitrary number of
774       hosts can be specified.  If a port is not specified for a given host,
775       it will default to 27017.
776
777       If multiple hosts are given in the seed list or discovered by talking
778       to servers in the seed list, they must all be replica set members or
779       must all be mongos servers for a sharded cluster.
780
781       A replica set MUST have the "replicaSet" option set to the replica set
782       name.
783
784       If there is only single host in the seed list and "replicaSet" is not
785       provided, the deployment is treated as a single server deployment and
786       all reads and writes will be sent to that host.
787
788       Providing a replica set member as a single host without the set name is
789       the way to get a "direct connection" for carrying out administrative
790       activities on that server.
791
792       The connection string may also have a username and password:
793
794           mongodb://username:password@host1:port1,host2:port2
795
796       The username and password must be URL-escaped.
797
798       A optional database name for authentication may be given:
799
800           mongodb://username:password@host1:port1,host2:port2/my_database
801
802       Finally, connection string options may be given as URI attribute pairs
803       in a query string:
804
805           mongodb://host1:port1,host2:port2/?ssl=1&wtimeoutMS=1000
806           mongodb://username:password@host1:port1,host2:port2/my_database?ssl=1&wtimeoutMS=1000
807
808       The currently supported connection string options are:
809
810           *appName *authMechanism *authMechanism.SERVICE_NAME *compressors
811           *connectTimeoutMS *journal *readPreference *readPreferenceTags
812           *replicaSet *ssl *w *wtimeoutMS *zlibCompressionLevel
813
814       See the official MongoDB documentation on connection strings for more
815       on the URI format and connection string options:
816       <http://docs.mongodb.org/manual/reference/connection-string/>.
817

SERVER SELECTION

819       For a single server deployment or a direct connection to a mongod or
820       mongos, all reads and writes and sent to that server.  Any read-
821       preference is ignored.
822
823       When connected to a deployment with multiple servers, such as a replica
824       set or sharded cluster, the driver chooses a server for operations
825       based on the type of operation (read or write), the types of servers
826       available and a read preference.
827
828       For a replica set deployment, writes are sent to the primary (if
829       available) and reads are sent to a server based on the
830       "read_preference" attribute, which defaults to sending reads to the
831       primary.  See MongoDB::ReadPreference for more.
832
833       For a sharded cluster reads and writes are distributed across mongos
834       servers in the seed list.  Any read preference is passed through to the
835       mongos and used by it when executing reads against shards.
836
837       If multiple servers can service an operation (e.g. multiple mongos
838       servers, or multiple replica set members), one is chosen at random from
839       within the "latency window".  The server with the shortest average
840       round-trip time (RTT) is always in the window.  Any servers with an
841       average round-trip time less than or equal to the shortest RTT plus the
842       "local_threshold_ms" are also in the latency window.
843
844       If a suitable server is not immediately available, what happens next
845       depends on the "server_selection_try_once" option.
846
847       If that option is true, a single topology scan will be performed.
848       Afterwards if a suitable server is available, it will be returned;
849       otherwise, an exception is thrown.
850
851       If that option is false, the driver will do topology scans repeatedly
852       looking for a suitable server.  When more than
853       "server_selection_timeout_ms" milliseconds have elapsed since the start
854       of server selection without a suitable server being found, an exception
855       is thrown.
856
857       Note: the actual maximum wait time for server selection could be as
858       long "server_selection_timeout_ms" plus the amount of time required to
859       do a topology scan.
860

SERVER MONITORING AND FAILOVER

862       When the client first needs to find a server for a database operation,
863       all servers from the "host" attribute are scanned to determine which
864       servers to monitor.  If the deployment is a replica set, additional
865       hosts may be discovered in this process.  Invalid hosts are dropped.
866
867       After the initial scan, whenever the servers have not been checked in
868       "heartbeat_frequency_ms" milliseconds, the scan will be repeated.  This
869       amortizes monitoring time over many of operations.  Additionally, if a
870       socket has been idle for a while, it will be checked before being used
871       for an operation.
872
873       If a server operation fails because of a "not master" or "node is
874       recovering" error, or if there is a network error or timeout, then the
875       server is flagged as unavailable and exception will be thrown.  See
876       MongoDB::Errors for exception types.
877
878       If the error is caught and handled, the next operation will rescan all
879       servers immediately to update its view of the topology.  The driver can
880       continue to function as long as servers are suitable per "SERVER
881       SELECTION".
882
883       When catching an exception, users must determine whether or not their
884       application should retry an operation based on the specific operation
885       attempted and other use-case-specific considerations.  For automating
886       retries despite exceptions, consider using the Try::Tiny::Retry module.
887

TRANSPORT LAYER SECURITY

889       Warning: industry best practices, and some regulations, require the use
890       of TLS 1.1 or newer.
891
892       Some operating systems or versions may not provide an OpenSSL version
893       new enough to support the latest TLS protocols.  If your OpenSSL
894       library version number is less than 1.0.1, then support for TLS 1.1 or
895       newer is not available. Contact your operating system vendor for a
896       solution or upgrade to a newer operating system distribution.
897
898       See also the documentation for Net::SSLeay for details on installing
899       and compiling against OpenSSL.
900
901       TLS connections in the driver rely on the default settings provided by
902       IO::Socket::SSL, but allow you to pass custom configuration to it.
903       Please read its documentation carefully to see how to control your TLS
904       configuration.
905

AUTHENTICATION

907       The MongoDB server provides several authentication mechanisms, though
908       some are only available in the Enterprise edition.
909
910       MongoDB client authentication is controlled via the "auth_mechanism"
911       attribute, which takes one of the following values:
912
913       NOTE: MONGODB-CR was deprecated with the release of MongoDB 3.6 and is
914       no longer supported by MongoDB 4.0.
915
916       ·   MONGODB-CR -- legacy username-password challenge-response (< 4.0)
917
918       ·   SCRAM-SHA-1 -- secure username-password challenge-response (3.0+)
919
920       ·   MONGODB-X509 -- SSL client certificate authentication (2.6+)
921
922       ·   PLAIN -- LDAP authentication via SASL PLAIN (Enterprise only)
923
924       ·   GSSAPI -- Kerberos authentication (Enterprise only)
925
926       The mechanism to use depends on the authentication configuration of the
927       server.  See the core documentation on authentication:
928       <http://docs.mongodb.org/manual/core/access-control/>.
929
930       Usage information for each mechanism is given below.
931
932   MONGODB-CR and SCRAM-SHA-1 (for username/password)
933       These mechanisms require a username and password, given either as
934       constructor attributes or in the "host" connection string.
935
936       If a username is provided and an authentication mechanism is not
937       specified, the client will use SCRAM-SHA-1 for version 3.0 or later
938       servers and will fall back to MONGODB-CR for older servers.
939
940           my $mc = MongoDB::MongoClient->new(
941               host => "mongodb://mongo.example.com/",
942               username => "johndoe",
943               password => "trustno1",
944           );
945
946           my $mc = MongoDB::MongoClient->new(
947               host => "mongodb://johndoe:trustno1@mongo.example.com/",
948           );
949
950       Usernames and passwords will be UTF-8 encoded before use.  The password
951       is never sent over the wire -- only a secure digest is used.  The
952       SCRAM-SHA-1 mechanism is the Salted Challenge Response Authentication
953       Mechanism defined in RFC 5802 <http://tools.ietf.org/html/rfc5802>.
954
955       The default database for authentication is 'admin'.  If another
956       database name should be used, specify it with the "db_name" attribute
957       or via the connection string.
958
959           db_name => auth_db
960
961           mongodb://johndoe:trustno1@mongo.example.com/auth_db
962
963   MONGODB-X509 (for SSL client certificate)
964       X509 authentication requires SSL support (IO::Socket::SSL), requires
965       that a client certificate be configured in the ssl parameters, and
966       requires specifying the "MONGODB-X509" authentication mechanism.
967
968           my $mc = MongoDB::MongoClient->new(
969               host => "mongodb://sslmongo.example.com/",
970               ssl => {
971                   SSL_ca_file   => "certs/ca.pem",
972                   SSL_cert_file => "certs/client.pem",
973               },
974               auth_mechanism => "MONGODB-X509",
975           );
976
977       Note: Since MongoDB Perl driver v1.8.0, you no longer need to specify a
978       "username" parameter for X509 authentication; the username will be
979       extracted automatically from the certificate.
980
981   PLAIN (for LDAP)
982       This mechanism requires a username and password, which will be UTF-8
983       encoded before use.  The "auth_mechanism" parameter must be given as a
984       constructor attribute or in the "host" connection string:
985
986           my $mc = MongoDB::MongoClient->new(
987               host => "mongodb://mongo.example.com/",
988               username => "johndoe",
989               password => "trustno1",
990               auth_mechanism => "PLAIN",
991           );
992
993           my $mc = MongoDB::MongoClient->new(
994               host => "mongodb://johndoe:trustno1@mongo.example.com/authMechanism=PLAIN",
995           );
996
997   GSSAPI (for Kerberos)
998       Kerberos authentication requires the CPAN module Authen::SASL and a
999       GSSAPI-capable backend.
1000
1001       On Debian systems, Authen::SASL may be available as
1002       "libauthen-sasl-perl"; on RHEL systems, it may be available as
1003       "perl-Authen-SASL".
1004
1005       The Authen::SASL::Perl backend comes with Authen::SASL and requires the
1006       GSSAPI CPAN module for GSSAPI support.  On Debian systems, this may be
1007       available as "libgssapi-perl"; on RHEL systems, it may be available as
1008       "perl-GSSAPI".
1009
1010       Installing the GSSAPI module from CPAN rather than an OS package
1011       requires "libkrb5" and the "krb5-config" utility (available for
1012       Debian/RHEL systems in the "libkrb5-dev" package).
1013
1014       Alternatively, the Authen::SASL::XS or Authen::SASL::Cyrus modules may
1015       be used.  Both rely on Cyrus "libsasl".  Authen::SASL::XS is preferred,
1016       but not yet available as an OS package.  Authen::SASL::Cyrus is
1017       available on Debian as "libauthen-sasl-cyrus-perl" and on RHEL as
1018       "perl-Authen-SASL-Cyrus".
1019
1020       Installing Authen::SASL::XS or Authen::SASL::Cyrus from CPAN requires
1021       "libsasl".  On Debian systems, it is available from "libsasl2-dev"; on
1022       RHEL, it is available in "cyrus-sasl-devel".
1023
1024       To use the GSSAPI mechanism, first run "kinit" to authenticate with the
1025       ticket granting service:
1026
1027           $ kinit johndoe@EXAMPLE.COM
1028
1029       Configure MongoDB::MongoClient with the principal name as the
1030       "username" parameter and specify 'GSSAPI' as the "auth_mechanism":
1031
1032           my $mc = MongoDB::MongoClient->new(
1033               host => 'mongodb://mongo.example.com',
1034               username => 'johndoe@EXAMPLE.COM',
1035               auth_mechanism => 'GSSAPI',
1036           );
1037
1038       Both can be specified in the "host" connection string, keeping in mind
1039       that the '@' in the principal name must be encoded as "%40":
1040
1041           my $mc = MongoDB::MongoClient->new(
1042               host =>
1043                 'mongodb://johndoe%40EXAMPLE.COM@mongo.example.com/?authMechanism=GSSAPI',
1044           );
1045
1046       The default service name is 'mongodb'.  It can be changed with the
1047       "auth_mechanism_properties" attribute or in the connection string.
1048
1049           auth_mechanism_properties => { SERVICE_NAME => 'other_service' }
1050
1051           mongodb://.../?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:other_service
1052

THREAD-SAFETY AND FORK-SAFETY

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

AUTHORS

1058       ·   David Golden <david@mongodb.com>
1059
1060       ·   Rassi <rassi@mongodb.com>
1061
1062       ·   Mike Friedman <friedo@friedo.com>
1063
1064       ·   Kristina Chodorow <k.chodorow@gmail.com>
1065
1066       ·   Florian Ragwitz <rafl@debian.org>
1067
1069       This software is Copyright (c) 2019 by MongoDB, Inc.
1070
1071       This is free software, licensed under:
1072
1073         The Apache License, Version 2.0, January 2004
1074
1075
1076
1077perl v5.28.1                      2019-02-07           MongoDB::MongoClient(3)
Impressum