1MongoDB::MongoClient(3)User Contributed Perl DocumentatioMnongoDB::MongoClient(3)
2
3
4
6 MongoDB::MongoClient - A connection to a MongoDB server or multi-server
7 deployment
8
10 version v2.2.2
11
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
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
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 NOTE: Options specified in the connection string take precedence over
76 options provided as constructor arguments.
77
78 Defaults to the connection string URI "mongodb://localhost:27017".
79
80 For IPv6 support, you must have a recent version of IO::Socket::IP
81 installed. This module ships with the Perl core since v5.20.0 and is
82 available on CPAN for older Perls.
83
84 app_name
85 This attribute specifies an application name that should be associated
86 with this client. The application name will be communicated to the
87 server as part of the initial connection handshake, and will appear in
88 connection-level and operation-level diagnostics on the server
89 generated on behalf of this client. This may be set in a connection
90 string with the "appName" option.
91
92 The default is the empty string, which indicates a lack of an
93 application name.
94
95 The application name must not exceed 128 bytes.
96
97 auth_mechanism
98 This attribute determines how the client authenticates with the server.
99 Valid values are:
100
101 • NONE
102
103 • DEFAULT
104
105 • MONGODB-CR
106
107 • MONGODB-X509
108
109 • GSSAPI
110
111 • PLAIN
112
113 • SCRAM-SHA-1
114
115 If not specified, then if no username or "authSource" URI option is
116 provided, it defaults to NONE. Otherwise, it is set to DEFAULT, which
117 chooses SCRAM-SHA-1 if available or MONGODB-CR otherwise.
118
119 This may be set in a connection string with the "authMechanism" option.
120
121 auth_mechanism_properties
122 This is an optional hash reference of authentication mechanism specific
123 properties. See "AUTHENTICATION" for details.
124
125 This may be set in a connection string with the
126 "authMechanismProperties" option. If given, the value must be
127 key/value pairs joined with a ":". Multiple pairs must be separated by
128 a comma. If ": or "," appear in a key or value, they must be URL
129 encoded.
130
131 bson_codec
132 An object that provides the "encode_one" and "decode_one" methods, such
133 as from BSON. It may be initialized with a hash reference that will be
134 coerced into a new BSON object.
135
136 If not provided, a BSON object with default values will be generated.
137
138 compressors
139 An array reference of compression type names. Currently, "zlib", "zstd"
140 and "snappy" are supported.
141
142 zlib_compression_level
143 An integer from "-1" to 9 specifying the compression level to use when
144 "compression" is set to "zlib".
145
146 Note: When the special value "-1" is given, the default compression
147 level will be used.
148
149 connect_timeout_ms
150 This attribute specifies the amount of time in milliseconds to wait for
151 a new connection to a server.
152
153 The default is 10,000 ms.
154
155 If set to a negative value, connection operations will block
156 indefinitely until the server replies or until the operating system
157 TCP/IP stack gives up (e.g. if the name can't resolve or there is no
158 process listening on the target host/port).
159
160 A zero value polls the socket during connection and is thus likely to
161 fail except when talking to a local process (and perhaps even then).
162
163 This may be set in a connection string with the "connectTimeoutMS"
164 option.
165
166 db_name
167 Optional. If an "auth_mechanism" requires a database for
168 authentication, this attribute will be used. Otherwise, it will be
169 ignored. Defaults to "admin".
170
171 This may be provided in the connection string URI as a path between the
172 authority and option parameter sections. For example, to authenticate
173 against the "admin" database (showing a configuration option only for
174 illustration):
175
176 mongodb://localhost/admin?readPreference=primary
177
178 heartbeat_frequency_ms
179 The time in milliseconds (non-negative) between scans of all servers to
180 check if they are up and update their latency. Defaults to 60,000 ms.
181
182 This may be set in a connection string with the "heartbeatFrequencyMS"
183 option.
184
185 j
186 If true, the client will block until write operations have been
187 committed to the server's journal. Prior to MongoDB 2.6, this option
188 was ignored if the server was running without journaling. Starting with
189 MongoDB 2.6, write operations will fail if this option is used when the
190 server is running without journaling.
191
192 This may be set in a connection string with the "journal" option as the
193 strings 'true' or 'false'.
194
195 local_threshold_ms
196 The width of the 'latency window': when choosing between multiple
197 suitable servers for an operation, the acceptable delta in milliseconds
198 (non-negative) between shortest and longest average round-trip times.
199 Servers within the latency window are selected randomly.
200
201 Set this to "0" to always select the server with the shortest average
202 round trip time. Set this to a very high value to always randomly
203 choose any known server.
204
205 Defaults to 15 ms.
206
207 See "SERVER SELECTION" for more details.
208
209 This may be set in a connection string with the "localThresholdMS"
210 option.
211
212 max_staleness_seconds
213 The "max_staleness_seconds" parameter represents the maximum
214 replication lag in seconds (wall clock time) that a secondary can
215 suffer and still be eligible for reads. The default is -1, which
216 disables staleness checks. Otherwise, it must be a positive integer.
217
218 Note: this will only be used for server versions 3.4 or greater, as
219 that was when support for staleness tracking was added.
220
221 If the read preference mode is 'primary', then "max_staleness_seconds"
222 must not be supplied.
223
224 The "max_staleness_seconds" must be at least the
225 "heartbeat_frequency_ms" plus 10 seconds (which is how often the server
226 makes idle writes to the oplog).
227
228 This may be set in a connection string with the "maxStalenessSeconds"
229 option.
230
231 max_time_ms
232 Specifies the maximum amount of time in (non-negative) milliseconds
233 that the server should use for working on a database command. Defaults
234 to 0, which disables this feature. Make sure this value is shorter
235 than "socket_timeout_ms".
236
237 Note: this will only be used for server versions 2.6 or greater, as
238 that was when the $maxTimeMS meta-operator was introduced.
239
240 You are strongly encouraged to set this variable if you know your
241 environment has MongoDB 2.6 or later, as getting a definitive error
242 response from the server is vastly preferred over a getting a network
243 socket timeout.
244
245 This may be set in a connection string with the "maxTimeMS" option.
246
247 monitoring_callback
248 Specifies a code reference used to receive monitoring events. See
249 MongoDB::Monitoring for more details.
250
251 password
252 If an "auth_mechanism" requires a password, this attribute will be
253 used. Otherwise, it will be ignored.
254
255 This may be provided in the connection string URI as a
256 "username:password" pair in the leading portion of the authority
257 section before a "@" character. For example, to authenticate as user
258 "mulder" with password "trustno1":
259
260 mongodb://mulder:trustno1@localhost
261
262 If the username or password have a ":" or "@" in it, they must be URL
263 encoded. An empty password still requires a ":" character.
264
265 port
266 If a network port is not specified as part of the "host" attribute,
267 this attribute provides the port to use. It defaults to 27107.
268
269 read_concern_level
270 The read concern level determines the consistency level required of
271 data being read.
272
273 The default level is "undef", which means the server will use its
274 configured default.
275
276 If the level is set to "local", reads will return the latest data a
277 server has locally.
278
279 Additional levels are storage engine specific. See Read Concern
280 <http://docs.mongodb.org/manual/search/?query=readConcern> in the
281 MongoDB documentation for more details.
282
283 This may be set in a connection string with the the "readConcernLevel"
284 option.
285
286 read_pref_mode
287 The read preference mode determines which server types are candidates
288 for a read operation. Valid values are:
289
290 • primary
291
292 • primaryPreferred
293
294 • secondary
295
296 • secondaryPreferred
297
298 • nearest
299
300 For core documentation on read preference see
301 <http://docs.mongodb.org/manual/core/read-preference/>.
302
303 This may be set in a connection string with the "readPreference"
304 option.
305
306 read_pref_tag_sets
307 The "read_pref_tag_sets" parameter is an ordered list of tag sets used
308 to restrict the eligibility of servers, such as for data center
309 awareness. It must be an array reference of hash references.
310
311 The application of "read_pref_tag_sets" varies depending on the
312 "read_pref_mode" parameter. If the "read_pref_mode" is 'primary', then
313 "read_pref_tag_sets" must not be supplied.
314
315 For core documentation on read preference see
316 <http://docs.mongodb.org/manual/core/read-preference/>.
317
318 This may be set in a connection string with the "readPreferenceTags"
319 option. If given, the value must be key/value pairs joined with a ":".
320 Multiple pairs must be separated by a comma. If ": or "," appear in a
321 key or value, they must be URL encoded. The "readPreferenceTags"
322 option may appear more than once, in which case each document will be
323 added to the tag set list.
324
325 replica_set_name
326 Specifies the replica set name to connect to. If this string is non-
327 empty, then the topology is treated as a replica set and all server
328 replica set names must match this or they will be removed from the
329 topology.
330
331 This may be set in a connection string with the "replicaSet" option.
332
333 retry_reads
334 retry_writes
335 Whether the client should use retryable writes for supported commands.
336 The default value is true, which means that commands which support
337 retryable writes will be retried on certain errors, such as "not
338 master" and "node is recovering" errors.
339
340 This may be set in a connection string with the "retryWrites" option.
341
342 Note that this is only supported on MongoDB > 3.6 in Replica Set or
343 Shard Clusters, and will be ignored on other deployments.
344
345 Unacknowledged write operations also do not support retryable writes,
346 even when retry_writes has been enabled.
347
348 The supported single statement write operations are currently as
349 follows:
350
351 • "insert_one"
352
353 • "update_one"
354
355 • "replace_one"
356
357 • "delete_one"
358
359 • "find_one_and_delete"
360
361 • "find_one_and_replace"
362
363 • "find_one_and_update"
364
365 The supported multi statement write operations are as follows:
366
367 • "insert_many"
368
369 • "bulk_write"
370
371 The multi statement operations may be ether ordered or unordered. Note
372 that for "bulk_write" operations, the request may not include
373 update_many or delete_many operations.
374
375 server_selection_timeout_ms
376 This attribute specifies the amount of time in milliseconds to wait for
377 a suitable server to be available for a read or write operation. If no
378 server is available within this time period, an exception will be
379 thrown.
380
381 The default is 30,000 ms.
382
383 See "SERVER SELECTION" for more details.
384
385 This may be set in a connection string with the
386 "serverSelectionTimeoutMS" option.
387
388 server_selection_try_once
389 This attribute controls whether the client will make only a single
390 attempt to find a suitable server for a read or write operation. The
391 default is true.
392
393 When true, the client will not use the "server_selection_timeout_ms".
394 Instead, if the topology information is stale and needs to be checked
395 or if no suitable server is available, the client will make a single
396 scan of all known servers to try to find a suitable one.
397
398 When false, the client will continually scan known servers until a
399 suitable server is found or the "serverSelectionTimeoutMS" is reached.
400
401 See "SERVER SELECTION" for more details.
402
403 This may be set in a connection string with the
404 "serverSelectionTryOnce" option.
405
406 server_selector
407 Optional. This takes a function that augments the server selection
408 rules. The function takes as a parameter a list of server descriptions
409 representing the suitable servers for the read or write operation, and
410 returns a list of server descriptions that should still be considered
411 suitable. Most users should rely on the default server selection
412 algorithm and should not need to set this attribute.
413
414 socket_check_interval_ms
415 If a socket to a server has not been used in this many milliseconds, an
416 "ismaster" command will be issued to check the status of the server
417 before issuing any reads or writes. Must be non-negative.
418
419 The default is 5,000 ms.
420
421 This may be set in a connection string with the "socketCheckIntervalMS"
422 option.
423
424 socket_timeout_ms
425 This attribute specifies the amount of time in milliseconds to wait for
426 a reply from the server before issuing a network exception.
427
428 The default is 30,000 ms.
429
430 If set to a negative value, socket operations will block indefinitely
431 until the server replies or until the operating system TCP/IP stack
432 gives up.
433
434 The driver automatically sets the TCP keepalive option when
435 initializing the socket. For keepalive related issues, check the
436 MongoDB documentation for Does TCP keepalive time affect MongoDB
437 Deployments? <https://docs.mongodb.com/v3.2/faq/diagnostics/#does-tcp-
438 keepalive-time-affect-mongodb-deployments>.
439
440 A zero value polls the socket for available data and is thus likely to
441 fail except when talking to a local process (and perhaps even then).
442
443 This may be set in a connection string with the "socketTimeoutMS"
444 option.
445
446 ssl
447 ssl => 1
448 ssl => \%ssl_options
449
450 This tells the driver that you are connecting to an SSL mongodb
451 instance.
452
453 You must have IO::Socket::SSL 1.42+ and Net::SSLeay 1.49+ installed for
454 SSL support.
455
456 The "ssl" attribute takes either a boolean value or a hash reference of
457 options to pass to IO::Socket::SSL. For example, to set a CA file to
458 validate the server certificate and set a client certificate for the
459 server to validate, you could set the attribute like this:
460
461 ssl => {
462 SSL_ca_file => "/path/to/ca.pem",
463 SSL_cert_file => "/path/to/client.pem",
464 }
465
466 If "SSL_ca_file" is not provided, server certificates are verified
467 against a default list of CAs, either Mozilla::CA or an operating-
468 system-specific default CA file. To disable verification, you can use
469 "SSL_verify_mode => 0x00".
470
471 You are strongly encouraged to use your own CA file for increased
472 security.
473
474 Server hostnames are also validated against the CN name in the server
475 certificate using "SSL_verifycn_scheme => 'http'". You can use the
476 scheme 'none' to disable this check.
477
478 Disabling certificate or hostname verification is a security risk and
479 is not recommended.
480
481 This may be set to the string 'true' or 'false' in a connection string
482 with the "ssl" option, which will enable ssl with default
483 configuration. (See connection string URI for additional TLS
484 configuration options.)
485
486 username
487 Optional username for this client connection. If this field is set,
488 the client will attempt to authenticate when connecting to servers.
489 Depending on the "auth_mechanism", the "password" field or other
490 attributes will need to be set for authentication to succeed.
491
492 This may be provided in the connection string URI as a
493 "username:password" pair in the leading portion of the authority
494 section before a "@" character. For example, to authenticate as user
495 "mulder" with password "trustno1":
496
497 mongodb://mulder:trustno1@localhost
498
499 If the username or password have a ":" or "@" in it, they must be URL
500 encoded. An empty password still requires a ":" character.
501
502 w
503 The client write concern.
504
505 • 0 Unacknowledged. MongoClient will NOT wait for an acknowledgment
506 that the server has received and processed the request. Older
507 documentation may refer to this as "fire-and-forget" mode. This
508 option is not recommended.
509
510 • 1 Acknowledged. MongoClient will wait until the primary MongoDB
511 acknowledges the write.
512
513 • 2 Replica acknowledged. MongoClient will wait until at least two
514 replicas (primary and one secondary) acknowledge the write. You can
515 set a higher number for more replicas.
516
517 • "all" All replicas acknowledged.
518
519 • "majority" A majority of replicas acknowledged.
520
521 If not set, the server default is used, which is typically "1".
522
523 In MongoDB v2.0+, you can "tag" replica members. With "tagging" you can
524 specify a custom write concern For more information see Data Center
525 Awareness <http://docs.mongodb.org/manual/data-center-awareness/>
526
527 This may be set in a connection string with the "w" option.
528
529 wtimeout
530 The number of milliseconds an operation should wait for "w" secondaries
531 to replicate it.
532
533 Defaults to 1000 (1 second). If you set this to undef, it could block
534 indefinitely (or until socket timeout is reached).
535
536 See "w" above for more information.
537
538 This may be set in a connection string with the "wTimeoutMS" option.
539
541 read_preference
542 Returns a MongoDB::ReadPreference object constructed from
543 "read_pref_mode" and "read_pref_tag_sets"
544
545 The use of "read_preference" as a mutator has been removed. Read
546 preference is read-only. If you need a different read preference for a
547 database or collection, you can specify that in "get_database" or
548 "get_collection".
549
550 write_concern
551 Returns a MongoDB::WriteConcern object constructed from "w",
552 "write_concern" and "j".
553
554 read_concern
555 Returns a MongoDB::ReadConcern object constructed from
556 "read_concern_level".
557
558 topology_type
559 Returns an enumerated topology type. If the "replica_set_name" is set,
560 the value will be either 'ReplicaSetWithPrimary' or
561 'ReplicaSetNoPrimary' (if the primary is down or not yet discovered).
562 Without "replica_set_name", if there is more than one server in the
563 list of hosts, the type will be 'Sharded'.
564
565 With only a single host and no replica set name, the topology type will
566 start as 'Direct' until the server is contacted the first time, after
567 which the type will be 'Sharded' for a mongos or 'Single' for
568 standalone server or direct connection to a replica set member.
569
570 connect
571 $client->connect;
572
573 Calling this method is unnecessary, as connections are established
574 automatically as needed. It is kept for backwards compatibility.
575 Calling it will check all servers in the deployment which ensures a
576 connection to any that are available.
577
578 See "reconnect" for a method that is useful when using forks or
579 threads.
580
581 disconnect
582 $client->disconnect;
583
584 Drops all connections to servers.
585
586 reconnect
587 $client->reconnect;
588
589 This method closes all connections to the server, as if "disconnect"
590 were called, and then immediately reconnects. It also clears the
591 session cache. Use this after forking or spawning off a new thread.
592
593 topology_status
594 $client->topology_status;
595 $client->topology_status( refresh => 1 );
596
597 Returns a hash reference with server topology information like this:
598
599 {
600 'topology_type' => 'ReplicaSetWithPrimary'
601 'replica_set_name' => 'foo',
602 'last_scan_time' => '1433766895.183241',
603 'servers' => [
604 {
605 'address' => 'localhost:50003',
606 'ewma_rtt_ms' => '0.223462326',
607 'type' => 'RSSecondary'
608 },
609 {
610 'address' => 'localhost:50437',
611 'ewma_rtt_ms' => '0.268435456',
612 'type' => 'RSArbiter'
613 },
614 {
615 'address' => 'localhost:50829',
616 'ewma_rtt_ms' => '0.737782272',
617 'type' => 'RSPrimary'
618 }
619 },
620 }
621
622 If the 'refresh' argument is true, then the topology will be scanned to
623 update server data before returning the hash reference.
624
625 start_session
626 $client->start_session;
627 $client->start_session( $options );
628
629 Returns a new MongoDB::ClientSession with the supplied options.
630
631 will throw a "MongoDB::ConfigurationError" if sessions are not
632 supported by the connected MongoDB deployment.
633
634 the options hash is an optional hash which can have the following keys:
635
636 • "causalConsistency" - Enable Causally Consistent reads for this
637 session. Defaults to true.
638
639 for more information see "options" in MongoDB::ClientSession.
640
641 list_databases
642 # get all information on all databases
643 my @dbs = $client->list_databases;
644
645 # get only the foo databases
646 my @foo_dbs = $client->list_databases({ filter => { name => qr/^foo/ } });
647
648 Lists all databases with information on each database. Supports
649 filtering by any of the output fields under the "filter" argument, such
650 as:
651
652 • "name"
653
654 • "sizeOnDisk"
655
656 • "empty"
657
658 • "shards"
659
660 database_names
661 my @dbs = $client->database_names;
662
663 # get only the foo database names
664 my @foo_dbs = $client->database_names({ filter => { name => qr/^foo/ } });
665
666 List of all database names on the MongoDB server. Supports filters in
667 the same way as "list_databases".
668
669 get_database, db
670 my $database = $client->get_database('foo');
671 my $database = $client->get_database('foo', $options);
672 my $database = $client->db('foo', $options);
673
674 Returns a MongoDB::Database instance for the database with the given
675 $name.
676
677 It takes an optional hash reference of options that are passed to the
678 MongoDB::Database constructor.
679
680 The "db" method is an alias for "get_database".
681
682 get_namespace, ns
683 my $collection = $client->get_namespace('test.foo');
684 my $collection = $client->get_namespace('test.foo', $options);
685 my $collection = $client->ns('test.foo', $options);
686
687 Returns a MongoDB::Collection instance for the given namespace. The
688 namespace has both the database name and the collection name separated
689 with a dot character.
690
691 This is a quick way to get a collection object if you don't need the
692 database object separately.
693
694 It takes an optional hash reference of options that are passed to the
695 MongoDB::Collection constructor. The intermediate MongoDB::Database
696 object will be created with default options.
697
698 The "ns" method is an alias for "get_namespace".
699
700 fsync(\%args)
701 $client->fsync();
702
703 A function that will forces the server to flush all pending writes to
704 the storage layer.
705
706 The fsync operation is synchronous by default, to run fsync
707 asynchronously, use the following form:
708
709 $client->fsync({async => 1});
710
711 The primary use of fsync is to lock the database during backup
712 operations. This will flush all data to the data storage layer and
713 block all write operations until you unlock the database. Note: you can
714 still read while the database is locked.
715
716 $conn->fsync({lock => 1});
717
718 fsync_unlock
719 $conn->fsync_unlock();
720
721 Unlocks a database server to allow writes and reverses the operation of
722 a $conn->fsync({lock => 1}); operation.
723
724 watch
725 Watches for changes on the cluster.
726
727 Perform an aggregation with an implicit initial $changeStream stage and
728 returns a MongoDB::ChangeStream result which can be used to iterate
729 over the changes in the cluster. This functionality is available since
730 MongoDB 4.0.
731
732 my $stream = $client->watch();
733 my $stream = $client->watch( \@pipeline );
734 my $stream = $client->watch( \@pipeline, \%options );
735
736 while (1) {
737
738 # This inner loop will only run until no more changes are
739 # available.
740 while (my $change = $stream->next) {
741 # process $change
742 }
743 }
744
745 The returned stream will not block forever waiting for changes. If you
746 want to respond to changes over a longer time use "maxAwaitTimeMS" and
747 regularly call "next" in a loop.
748
749 See "watch" in MongoDB::Collection for details on usage and available
750 options.
751
753 MongoDB can operate as a single server or as a distributed system. One
754 or more servers that collectively provide access to a single logical
755 set of MongoDB databases are referred to as a "deployment".
756
757 There are three types of deployments:
758
759 • Single server – a stand-alone mongod database
760
761 • Replica set – a set of mongod databases with data replication and
762 fail-over capability
763
764 • Sharded cluster – a distributed deployment that spreads data across
765 one or more shards, each of which can be a replica set. Clients
766 communicate with a mongos process that routes operations to the
767 correct share.
768
769 The state of a deployment, including its type, which servers are
770 members, the server types of members and the round-trip network latency
771 to members is referred to as the "topology" of the deployment.
772
773 To the greatest extent possible, the MongoDB driver abstracts away the
774 details of communicating with different deployment types. It
775 determines the deployment topology through a combination of the
776 connection string, configuration options and direct discovery
777 communicating with servers in the deployment.
778
780 MongoDB uses a pseudo-URI connection string to specify one or more
781 servers to connect to, along with configuration options.
782
783 NOTE: any non-printable ASCII characters should be UTF-8 encoded and
784 converted URL-escaped characters.
785
786 To connect to more than one database server, provide host or host:port
787 pairs as a comma separated list:
788
789 mongodb://host1[:port1][,host2[:port2],...[,hostN[:portN]]]
790
791 This list is referred to as the "seed list". An arbitrary number of
792 hosts can be specified. If a port is not specified for a given host,
793 it will default to 27017.
794
795 If multiple hosts are given in the seed list or discovered by talking
796 to servers in the seed list, they must all be replica set members or
797 must all be mongos servers for a sharded cluster.
798
799 A replica set MUST have the "replicaSet" option set to the replica set
800 name.
801
802 If there is only single host in the seed list and "replicaSet" is not
803 provided, the deployment is treated as a single server deployment and
804 all reads and writes will be sent to that host.
805
806 Providing a replica set member as a single host without the set name is
807 the way to get a "direct connection" for carrying out administrative
808 activities on that server.
809
810 The connection string may also have a username and password:
811
812 mongodb://username:password@host1:port1,host2:port2
813
814 The username and password must be URL-escaped.
815
816 A optional database name for authentication may be given:
817
818 mongodb://username:password@host1:port1,host2:port2/my_database
819
820 Finally, connection string options may be given as URI attribute pairs
821 in a query string:
822
823 mongodb://host1:port1,host2:port2/?ssl=1&wtimeoutMS=1000
824 mongodb://username:password@host1:port1,host2:port2/my_database?ssl=1&wtimeoutMS=1000
825
826 The currently supported connection string options are:
827
828 • "appName"
829
830 • "authMechanism"
831
832 • "authMechanismProperties"
833
834 • "authSource"
835
836 • "compressors"
837
838 • "connect"
839
840 • "connectTimeoutMS"
841
842 • "heartbeatFrequencyMS"
843
844 • "journal"
845
846 • "localThresholdMS"
847
848 • "maxStalenessSeconds"
849
850 • "maxTimeMS"
851
852 • "readConcernLevel"
853
854 • "readPreference"
855
856 • "readPreferenceTags"
857
858 • "replicaSet"
859
860 • "retryReads"
861
862 • "retryWrites"
863
864 • "serverSelectionTimeoutMS"
865
866 • "serverSelectionTryOnce"
867
868 • "socketCheckIntervalMS"
869
870 • "socketTimeoutMS"
871
872 • "ssl"
873
874 • "tls" (an alias for "ssl")
875
876 • "tlsAllowInvalidCertificates"
877
878 • "tlsAllowInvalidHostnames"
879
880 • "tlsCAFile"
881
882 • "tlsCertificateKeyFile"
883
884 • "tlsCertificateKeyFilePassword"
885
886 • "tlsInsecure"
887
888 • "w"
889
890 • "wTimeoutMS"
891
892 • "zlibCompressionLevel"
893
894 NOTE: Options specified in the connection string take precedence over
895 options provided as constructor arguments.
896
897 See the official MongoDB documentation on connection strings for more
898 on the URI format and connection string options:
899 <http://docs.mongodb.org/manual/reference/connection-string/>.
900
902 For a single server deployment or a direct connection to a mongod or
903 mongos, all reads and writes are sent to that server. Any read-
904 preference is ignored.
905
906 When connected to a deployment with multiple servers, such as a replica
907 set or sharded cluster, the driver chooses a server for operations
908 based on the type of operation (read or write), application-provided
909 server selector, the types of servers available and a read preference.
910
911 For a replica set deployment, writes are sent to the primary (if
912 available) and reads are sent to a server based on the
913 "read_preference" attribute, which defaults to sending reads to the
914 primary. See MongoDB::ReadPreference for more.
915
916 For a sharded cluster reads and writes are distributed across mongos
917 servers in the seed list. Any read preference is passed through to the
918 mongos and used by it when executing reads against shards.
919
920 If multiple servers can service an operation (e.g. multiple mongos
921 servers, or multiple replica set members), one is chosen by filtering
922 with server selector and then at random from within the "latency
923 window". The server with the shortest average round-trip time (RTT) is
924 always in the window. Any servers with an average round-trip time less
925 than or equal to the shortest RTT plus the "local_threshold_ms" are
926 also in the latency window.
927
928 If a suitable server is not immediately available, what happens next
929 depends on the "server_selection_try_once" option.
930
931 If that option is true, a single topology scan will be performed.
932 Afterwards if a suitable server is available, it will be returned;
933 otherwise, an exception is thrown.
934
935 If that option is false, the driver will do topology scans repeatedly
936 looking for a suitable server. When more than
937 "server_selection_timeout_ms" milliseconds have elapsed since the start
938 of server selection without a suitable server being found, an exception
939 is thrown.
940
941 Note: the actual maximum wait time for server selection could be as
942 long "server_selection_timeout_ms" plus the amount of time required to
943 do a topology scan.
944
946 When the client first needs to find a server for a database operation,
947 all servers from the "host" attribute are scanned to determine which
948 servers to monitor. If the deployment is a replica set, additional
949 hosts may be discovered in this process. Invalid hosts are dropped.
950
951 After the initial scan, whenever the servers have not been checked in
952 "heartbeat_frequency_ms" milliseconds, the scan will be repeated. This
953 amortizes monitoring time over many of operations. Additionally, if a
954 socket has been idle for a while, it will be checked before being used
955 for an operation.
956
957 If a server operation fails because of a "not master" or "node is
958 recovering" error, or if there is a network error or timeout, then the
959 server is flagged as unavailable and exception will be thrown. See
960 MongoDB::Errors for exception types.
961
962 If the error is caught and handled, the next operation will rescan all
963 servers immediately to update its view of the topology. The driver can
964 continue to function as long as servers are suitable per "SERVER
965 SELECTION".
966
967 When catching an exception, users must determine whether or not their
968 application should retry an operation based on the specific operation
969 attempted and other use-case-specific considerations. For automating
970 retries despite exceptions, consider using the Try::Tiny::Retry module.
971
973 Warning: industry best practices, and some regulations, require the use
974 of TLS 1.1 or newer.
975
976 Some operating systems or versions may not provide an OpenSSL version
977 new enough to support the latest TLS protocols. If your OpenSSL
978 library version number is less than 1.0.1, then support for TLS 1.1 or
979 newer is not available. Contact your operating system vendor for a
980 solution or upgrade to a newer operating system distribution.
981
982 See also the documentation for Net::SSLeay for details on installing
983 and compiling against OpenSSL.
984
985 TLS connections in the driver rely on the default settings provided by
986 IO::Socket::SSL, but allow you to pass custom configuration to it.
987 Please read its documentation carefully to see how to control your TLS
988 configuration.
989
991 The MongoDB server provides several authentication mechanisms, though
992 some are only available in the Enterprise edition.
993
994 MongoDB client authentication is controlled via the "auth_mechanism"
995 attribute, which takes one of the following values:
996
997 NOTE: MONGODB-CR was deprecated with the release of MongoDB 3.6 and is
998 no longer supported by MongoDB 4.0.
999
1000 • MONGODB-CR -- legacy username-password challenge-response (< 4.0)
1001
1002 • SCRAM-SHA-1 -- secure username-password challenge-response (3.0+)
1003
1004 • MONGODB-X509 -- SSL client certificate authentication (2.6+)
1005
1006 • PLAIN -- LDAP authentication via SASL PLAIN (Enterprise only)
1007
1008 • GSSAPI -- Kerberos authentication (Enterprise only)
1009
1010 The mechanism to use depends on the authentication configuration of the
1011 server. See the core documentation on authentication:
1012 <http://docs.mongodb.org/manual/core/access-control/>.
1013
1014 Usage information for each mechanism is given below.
1015
1016 MONGODB-CR and SCRAM-SHA-1 (for username/password)
1017 These mechanisms require a username and password, given either as
1018 constructor attributes or in the "host" connection string.
1019
1020 If a username is provided and an authentication mechanism is not
1021 specified, the client will use SCRAM-SHA-1 for version 3.0 or later
1022 servers and will fall back to MONGODB-CR for older servers.
1023
1024 my $mc = MongoDB::MongoClient->new(
1025 host => "mongodb://mongo.example.com/",
1026 username => "johndoe",
1027 password => "trustno1",
1028 );
1029
1030 my $mc = MongoDB::MongoClient->new(
1031 host => "mongodb://johndoe:trustno1@mongo.example.com/",
1032 );
1033
1034 Usernames and passwords will be UTF-8 encoded before use. The password
1035 is never sent over the wire -- only a secure digest is used. The
1036 SCRAM-SHA-1 mechanism is the Salted Challenge Response Authentication
1037 Mechanism defined in RFC 5802 <http://tools.ietf.org/html/rfc5802>.
1038
1039 The default database for authentication is 'admin'. If another
1040 database name should be used, specify it with the "db_name" attribute
1041 or via the connection string.
1042
1043 db_name => auth_db
1044
1045 mongodb://johndoe:trustno1@mongo.example.com/auth_db
1046
1047 MONGODB-X509 (for SSL client certificate)
1048 X509 authentication requires SSL support (IO::Socket::SSL), requires
1049 that a client certificate be configured in the ssl parameters, and
1050 requires specifying the "MONGODB-X509" authentication mechanism.
1051
1052 my $mc = MongoDB::MongoClient->new(
1053 host => "mongodb://sslmongo.example.com/",
1054 ssl => {
1055 SSL_ca_file => "certs/ca.pem",
1056 SSL_cert_file => "certs/client.pem",
1057 },
1058 auth_mechanism => "MONGODB-X509",
1059 );
1060
1061 Note: Since MongoDB Perl driver v1.8.0, you no longer need to specify a
1062 "username" parameter for X509 authentication; the username will be
1063 extracted automatically from the certificate.
1064
1065 PLAIN (for LDAP)
1066 This mechanism requires a username and password, which will be UTF-8
1067 encoded before use. The "auth_mechanism" parameter must be given as a
1068 constructor attribute or in the "host" connection string:
1069
1070 my $mc = MongoDB::MongoClient->new(
1071 host => "mongodb://mongo.example.com/",
1072 username => "johndoe",
1073 password => "trustno1",
1074 auth_mechanism => "PLAIN",
1075 );
1076
1077 my $mc = MongoDB::MongoClient->new(
1078 host => "mongodb://johndoe:trustno1@mongo.example.com/authMechanism=PLAIN",
1079 );
1080
1081 GSSAPI (for Kerberos)
1082 Kerberos authentication requires the CPAN module Authen::SASL and a
1083 GSSAPI-capable backend.
1084
1085 On Debian systems, Authen::SASL may be available as
1086 "libauthen-sasl-perl"; on RHEL systems, it may be available as
1087 "perl-Authen-SASL".
1088
1089 The Authen::SASL::Perl backend comes with Authen::SASL and requires the
1090 GSSAPI CPAN module for GSSAPI support. On Debian systems, this may be
1091 available as "libgssapi-perl"; on RHEL systems, it may be available as
1092 "perl-GSSAPI".
1093
1094 Installing the GSSAPI module from CPAN rather than an OS package
1095 requires "libkrb5" and the "krb5-config" utility (available for
1096 Debian/RHEL systems in the "libkrb5-dev" package).
1097
1098 Alternatively, the Authen::SASL::XS or Authen::SASL::Cyrus modules may
1099 be used. Both rely on Cyrus "libsasl". Authen::SASL::XS is preferred,
1100 but not yet available as an OS package. Authen::SASL::Cyrus is
1101 available on Debian as "libauthen-sasl-cyrus-perl" and on RHEL as
1102 "perl-Authen-SASL-Cyrus".
1103
1104 Installing Authen::SASL::XS or Authen::SASL::Cyrus from CPAN requires
1105 "libsasl". On Debian systems, it is available from "libsasl2-dev"; on
1106 RHEL, it is available in "cyrus-sasl-devel".
1107
1108 To use the GSSAPI mechanism, first run "kinit" to authenticate with the
1109 ticket granting service:
1110
1111 $ kinit johndoe@EXAMPLE.COM
1112
1113 Configure MongoDB::MongoClient with the principal name as the
1114 "username" parameter and specify 'GSSAPI' as the "auth_mechanism":
1115
1116 my $mc = MongoDB::MongoClient->new(
1117 host => 'mongodb://mongo.example.com',
1118 username => 'johndoe@EXAMPLE.COM',
1119 auth_mechanism => 'GSSAPI',
1120 );
1121
1122 Both can be specified in the "host" connection string, keeping in mind
1123 that the '@' in the principal name must be encoded as "%40":
1124
1125 my $mc = MongoDB::MongoClient->new(
1126 host =>
1127 'mongodb://johndoe%40EXAMPLE.COM@mongo.example.com/?authMechanism=GSSAPI',
1128 );
1129
1130 The default service name is 'mongodb'. It can be changed with the
1131 "auth_mechanism_properties" attribute or in the connection string.
1132
1133 auth_mechanism_properties => { SERVICE_NAME => 'other_service' }
1134
1135 mongodb://.../?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:other_service
1136
1138 You MUST call the "reconnect" method on any MongoDB::MongoClient
1139 objects after forking or spawning a thread.
1140
1141 NOTE: Per threads documentation, use of Perl threads is discouraged by
1142 the maintainers of Perl and the MongoDB Perl driver does not test or
1143 provide support for use with threads.
1144
1146 • David Golden <david@mongodb.com>
1147
1148 • Rassi <rassi@mongodb.com>
1149
1150 • Mike Friedman <friedo@friedo.com>
1151
1152 • Kristina Chodorow <k.chodorow@gmail.com>
1153
1154 • Florian Ragwitz <rafl@debian.org>
1155
1157 This software is Copyright (c) 2020 by MongoDB, Inc.
1158
1159 This is free software, licensed under:
1160
1161 The Apache License, Version 2.0, January 2004
1162
1163
1164
1165perl v5.34.0 2021-07-22 MongoDB::MongoClient(3)