-
Notifications
You must be signed in to change notification settings - Fork 534
/
Copy pathcreate-client.txt
2167 lines (1608 loc) · 83.4 KB
/
create-client.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
*****************
Creating a Client
*****************
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
Using ``Mongo::Client``
=======================
To connect to a MongoDB deployment, create a ``Mongo::Client`` object.
Provide a list of hosts and options or a :manual:`connection string URI
</reference/connection-string/>` to the``Mongo::Client`` constructor.
The client's selected database defaults to ``admin``.
By default, the driver will automatically detect the topology used by the
deployment and connect appropriately.
To connect to a local standalone MongoDB deployment, specify the host and
port of the server. In most cases you would also specify the database name
to connect to; if no database name is specified, the client will use the
``admin`` database:
.. code-block:: ruby
Mongo::Client.new([ '127.0.0.1:27017' ], database: 'mydb')
# Or using the URI syntax:
Mongo::Client.new("mongodb://127.0.0.1:27017/mydb")
.. note::
The hostname ``localhost`` is treated specially by the driver and will
be resolved to IPv4 addresses only.
To `connect to MongoDB Atlas <https://docs.atlas.mongodb.com/driver-connection/>`_,
specify the Atlas deployment URI:
.. code-block:: ruby
Mongo::Client.new("mongodb+srv://username:[email protected]/mydb?w=majority")
The driver will discover all nodes in the cluster and connect to them as
needed.
Block Syntax
------------
Another way to create a Mongo::Client object is to use the block syntax:
.. code-block:: ruby
Mongo::Client.new(...) do |client|
# work with the client
end
Note that when creating a client using this syntax, the client is automatically closed after the block finishes executing.
Database Selection
==================
By default, the client will connect to the ``admin`` database.
The ``admin`` database is a special database in MongoDB often used for
administrative tasks and storing administrative data such as users and
roles (although users and roles may also be defined in other databases).
In a sharded cluster, the ``admin`` database
:manual:`exists on the config servers </core/sharded-cluster-config-servers/#read-and-write-operations-on-config-servers>`
rather than the shard servers. Although it is possible to use the ``admin``
database for ordinary operations (such as storing application data), this
is not recommended and the application should explicitly specify the
database it wishes to use.
The database can be specified during ``Client`` construction:
.. code-block:: ruby
# Using Ruby client options:
client = Mongo::Client.new(['localhost'], database: 'mydb')
# Using a MongoDB URI:
client = Mongo::Client.new('mongodb://localhost/mydb')
Given a ``Client`` instance, the ``use`` method can be invoked to obtain a
new ``Client`` instance configured with the specified database:
.. code-block:: ruby
client = Mongo::Client.new(['localhost'], database: 'mydb')
admin_client = client.use('admin')
# Issue an administrative command
admin_client.database.command(replSetGetConfig: 1).documents.first
There are other special databases in MongoDB which should be only used for
their stated purposes:
- The :manual:`config </reference/config-database/>` database.
- The :manual:`local </reference/local-database/>` database.
- The ``$external`` database, which is used with :ref:`PLAIN <plain>`,
:ref:`Kerberos <kerberos>` and :ref:`X.509 <x.509>` authentication
mechanisms.
Connection Types
================
The driver will, by default, discover the type of deployment it is instructed
to connect to (except for load-balanced deployments)
and behave in the manner that matches the deployment type.
The subsections below describe how the driver behaves in each of the deployment
types as well as how to force particular behavior, bypassing automatic
deployment type detection.
Note that the detection of deployment type happens when the driver receives
the first reply from any of the servers it is instructed to connect to
(unless the load-balancing mode is requested, see below). The driver will
remain in the discovered or configured topology even if the underlying
deployment is replaced by one of a different type. In particular, when
replacing a replica set with a sharded cluster at the same address
the client instance must be recreated (such as by restarting the application)
for it to communicate with the sharded cluster.
Automatic discovery of load-balanced deployments is currently not supported.
Load-balanced deployments will be treated as deployments of their underlying
type, which would generally be sharded clusters. The driver will fail to
correctly operate when treating a load-balanced deployment as a sharded
cluster, therefore when the deployment is a load-balanced one the client
must be explicitly configured to :ref:`connect to a load balancer
<load-balancer-connection>`.
Standalone Server Connection
----------------------------
If the deployment is a single server, also known as a standalone deployment,
all operations will be directed to the specified server.
If the server is shut down and replaced by a replica set node, the driver
will continue sending all operations to that node, even if the node is or
becomes a secondary.
To force a standalone connection, see the :ref:`direct connection
<direct-connection>` section below.
.. _connect-replica-set:
Replica Set Connection
----------------------
When connecting to a :manual:`replica set</replication/>`, it is sufficient
to pass the address of any node in the replica set to the driver.
The node does not have to be the primary and it may be a hidden node.
The driver will then automatically discover the remaining nodes.
However, it is recommended to specify all nodes that are part of the
replica set, so that in the event of one or more nodes being unavailable
(for example, due to maintenance or reconfiguration) the driver can still
connect to the replica set.
Replica set connection examples:
.. code-block:: ruby
Mongo::Client.new([ '127.0.0.1:27017' ], database: 'mydb')
Mongo::Client.new([ '127.0.0.1:27017', '127.0.0.1:27018' ], database: 'mydb')
# Or using the URI syntax:
Mongo::Client.new("mongodb://127.0.0.1:27017,127.0.0.1:27018/mydb")
To make the driver verify the replica set name upon connection, pass it using
the ``replica_set`` Ruby option or the ``replicaSet`` URI option:
.. code-block:: ruby
Mongo::Client.new([ '127.0.0.1:27017', '127.0.0.1:27018' ],
database: 'mydb', replica_set: 'myapp')
# Or using the URI syntax:
Mongo::Client.new("mongodb://127.0.0.1:27017,127.0.0.1:27018/mydb?replicaSet=myapp")
If the deployment is not a replica set or uses a different replica set name,
all operations will fail (until the expected replica set is returned by
the servers).
It is also possible to force a replica set connection without specifying
the replica set name. Doing so is generally unnecessary and is deprecated:
.. code-block:: ruby
Mongo::Client.new([ '127.0.0.1:27017', '127.0.0.1:27018' ],
database: 'mydb', connect: :replica_set)
# Or using the URI syntax:
Mongo::Client.new("mongodb://127.0.0.1:27017,127.0.0.1:27018/mydb?connect=replica_set")
To connect to a MongoDB Atlas cluster which is deployed as a replica set,
connect to the URI:
.. code-block:: ruby
Mongo::Client.new("mongodb+srv://username:[email protected]/test?w=majority")
Please review the :ref:`SRV URI notes <srv-uri-notes>` if using SRV URIs.
.. _connect-sharded-cluster:
Sharded Cluster Connection
--------------------------
To connect to a :manual:`sharded cluster</sharding/>` deployment, specify
the addresses of the ``mongos`` routers:
.. code-block:: ruby
Mongo::Client.new([ '1.2.3.4:27017', '1.2.3.5:27017' ], database: 'mydb')
Mongo::Client.new("mongodb://1.2.3.4:27017,1.2.3.5:27017/mydb")
Note that unlike a replica set connection, you may choose to connect to a
subset of the ``mongos`` routers that exist in the deployment. The driver
will monitor each router and will use the ones that are available
(i.e., the driver will generally handle individual routers becoming
unavailable due to failures or maintenance). When specifying the list of
routers explicitly, the driver will not discover remaining routers that
may be configured and will not attempt to connect to them.
The driver will automatically balance the operation load among the routers
it is aware of.
To connect to a MongoDB Atlas cluster which is deployed as a sharded cluster,
connect to the URI:
.. code-block:: ruby
Mongo::Client.new("mongodb+srv://username:[email protected]/test?w=majority")
When the driver connects to a sharded cluster via an SRV URI, it will
periodically poll the SRV records of the address specified in the URI
for changes and will automatically add and remove the ``mongos`` hosts
to/from its list of servers as they are added and removed to/from the
sharded cluster.
To force a sharded cluster connection, use the ``connect: :sharded``
option. Doing so is generally unnecessary and is deprecated:
.. code-block:: ruby
Mongo::Client.new([ '127.0.0.1:27017', '127.0.0.1:27018' ],
database: 'mydb', connect: :sharded)
# Or using the URI syntax:
Mongo::Client.new("mongodb://127.0.0.1:27017,127.0.0.1:27018/mydb?connect=sharded")
Please review the :ref:`SRV URI notes <srv-uri-notes>` if using SRV URIs.
.. _direct-connection:
Direct Connection
-----------------
To disable the deployment type discovery and force all operations to be
performed on a particular server, specify the ``direct_connection`` option:
.. code-block:: ruby
Mongo::Client.new([ '1.2.3.4:27017' ], database: 'mydb', direct_connection: true)
# Or using the URI syntax:
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?directConnection=true")
Alternatively, the deprecated ``connect: :direct`` option is equivalent:
.. code-block:: ruby
Mongo::Client.new([ '1.2.3.4:27017' ], database: 'mydb', connect: :direct)
# Or using the URI syntax:
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?connect=direct")
The direct connection mode is most useful for performing operations on a
particular replica set node, although it also permits the underlying server
to change type (e.g. from a replica set node to a ``mongos`` router, or vice
versa).
.. _load-balancer-connection:
Load Balancer Connection
------------------------
Unlike other deployment types, the driver does not currently automatically
detect a load-balanced deployment.
To connect to a load balancer, specify the ``load_balanced: true`` Ruby option
or the ``loadBalanced=true`` URI option:
.. code-block:: ruby
Mongo::Client.new([ '1.2.3.4:27017' ], database: 'mydb', load_balanced: true)
# Or using the URI syntax:
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?loadBalanced=true")
When using these options, if the specified server is not a load balancer,
the client will fail all operations (until the server becomes a load balancer).
To treat the server as a load balancer even if it doesn't identify as such,
use the ``connect: :load_balanced`` Ruby option or the ``connect=load_balanced``
URI option:
.. code-block:: ruby
Mongo::Client.new([ '1.2.3.4:27017' ],
database: 'mydb', load_balanced: true, connect: :load_balanced)
# Or using the URI syntax:
Mongo::Client.new("mongodb://1.2.3.4:27017/mydb?loadBalanced=true&connect=load_balanced")
MongoDB Atlas Connection
------------------------
To connect to a MongoDB deployment on Atlas, first create a ``Mongo::Client`` instance using your
cluster's connection string and other client options.
You can set the `Stable API <https://www.mongodb.com/docs/manual/reference/stable-api/>`_ version as
a client option to avoid breaking changes when you upgrade to a new server version.
The following code shows how you can specify the connection string and the Stable API client option
when connecting to a MongoDB deployment and verify that the connection is successful:
.. code-block:: ruby
require 'mongo'
# Replace the placeholders with your credentials
uri = "mongodb+srv://<username>:<password>@cluster0.sample.mongodb.net/?retryWrites=true&w=majority"
# Set the server_api field of the options object to Stable API version 1
options = { server_api: { version: "1" } }
# Create a new client and connect to the server
client = Mongo::Client.new(uri, options)
# Send a ping to confirm a successful connection
begin
admin_client = client.use('admin')
result = admin_client.database.command(ping: 1).documents.first
puts "Pinged your deployment. You successfully connected to MongoDB!"
rescue Mongo::Error::OperationFailure => ex
puts ex
ensure
client.close
end
Connect to MongoDB Atlas from AWS Lambda
----------------------------------------
To learn how to connect to Atlas from AWS Lambda, see the
`Manage Connections with AWS Lambda <https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/>`__
documentation.
.. _srv-uri-notes:
SRV URI Notes
=============
When the driver connects to a
:manual:`mongodb+srv protocol <reference/connection-string/#dns-seedlist-connection-format>`
URI, keep in mind the following:
1. SRV URI lookup is performed synchronously when the client is constructed.
If this lookup fails for any reason, client construction will fail with an
exception. When a client is constructed with a list of hosts, the driver
will attempt to contact and monitor those hosts for as long as the client
object exists. If one of these hosts does not resolve initially but becomes
resolvable later, the driver will be able to establish a connection to such
a host when it becomes available. The initial SRV URI lookup must succeed
on the first attempt; subsequent host lookups will be retried by the driver
as needed.
2. The driver looks up URI options in the DNS TXT records corresponding to the
SRV records. These options can be overridden by URI options specified in the
URI and by Ruby options, in this order.
3. Because the URI options are retrieved in a separate DNS query from the
SRV lookup, in environments with unreliable network connectivity
the URI option query may fail when the SRV lookup succeeds. Such a failure
would cause the driver to use the wrong auth source leading to
authentication failures. This can be worked around by explicitly specifying
the auth source:
.. code-block:: ruby
Mongo::Client.new("mongodb+srv://username:[email protected]/test?w=majority&authSource=admin")
4. If the topology of the constructed ``Client`` object is unknown or a
sharded cluster, the driver will begin monitoring the specified SRV DNS
records for changes and will automatically update the list of servers in the
cluster. The updates will stop if the topology becomes a single or a replica
set.
.. _client-options:
Client Options
==============
``Mongo::Client``'s constructor accepts a number of options configuring the
behavior of the driver. The options can be provided in the options hash as
Ruby options, in the URI as URI options, or both. If both a Ruby option and
the analogous URI option are provided, the Ruby option takes precedence.
Ruby Options
------------
.. note::
The options passed directly should be symbols.
.. note::
Unless otherwise specified, Ruby options that deal with times are given in
seconds.
.. list-table::
:header-rows: 1
:widths: 25 40 10 15
* - Option
- Description
- Type
- Default
* - ``:app_name``
- Application name that is printed to the mongod logs upon establishing a connection
in server versions >= 3.4.
- ``String``
- none
* - ``:auth_mech``
- Specifies the authenticaion mechanism to use. Can be one of:
``:gssapi``, ``:mongodb_cr``, ``:mongodb_x509``, ``:plain``,
``:scram``, ``:scram256``. GSSAPI (Kerberos) authentication
:ref:`requires additional dependencies <kerberos>`.
- ``Symbol``
- If user credentials are not supplied, ``nil``. If user credentials
are supplied, the default depends on server version.
MongoDB 4.0 and later: ``:scram256`` if user credentials correspond
to a user which supports SCRAM-SHA-256 authentication, otherwise
``:scram``.
MongoDB 3.0-3.6: ``:scram``.
MongoDB 2.6: ``:mongodb_cr``
* - ``:auth_mech_properties``
- Provides additional authentication mechanism properties.
The keys in properties are interpreted case-insensitively.
When the client is created, keys are lowercased.
- ``Hash``
- When using the GSSAPI authentication mechanism, the default properties
are ``{service_name: "mongodb"}``. Otherwise the default is nil.
* - ``:auth_source``
- Specifies the authentication source.
- ``String``
- For MongoDB 2.6 and later: **admin** if credentials are
supplied, otherwise the current database
* - ``:auto_encryption_options``
- A ``Hash`` of options for configuring automatic encryption.
- ``:key_vault_client`` - A client connected to the MongoDB instance
storing the encryption data keys (``Mongo::Client``, defaults to the
top-level client instance).
- ``:key_vault_namespace`` - The namespace of the key vault collection
in the format ``"database.collection"`` (``String``, required).
- ``:kms_providers`` - Key management service configuration information.
One or both of the keys ``:local`` and ``:aws`` must be specified
(``Hash``, required). See the "The ``kms_providers`` option`` section of the
:ref:`Client-Side Encryption tutorial<client-side-encryption>` for more
information about this option.
- ``:schema_map`` - The JSONSchema for one or more collections specifying
which fields should be encrypted (``Hash``, optional, defaults to ``nil``).
- ``:bypass_auto_encryption`` - Whether to skip automatic encryption when
performing database operations (``Boolean``, defaults to ``false``).
- ``:extra_options`` - Options related to spawning mongocryptd (``Hash``,
optional, defaults to ``nil``).
For more information about formatting these options, see the
"Auto-Encryption Options" section of the :ref:`Client-Side Encryption tutorial<client-side-encryption>`.
- ``Hash``
- none
* - ``:bg_error_backtrace``
- Experimental. Controls whether and how backtraces are logged when
errors occur in background threads. If ``true``, the driver will log
complete backtraces. If set to a positive integer, the driver will
log up to that many backtrace lines. If set to ``false`` or ``nil``,
no backtraces will be logged. Other values are an error.
- ``true``, ``false``, ``nil``, ``Integer``
- none
* - ``:compressors``
- A list of potential compressors to use, in order of preference.
Please see below for details on how the driver implements compression.
- ``Array<String>``
- none
* - ``:warn_compression_disabled``
- By default, the driver warns if you have not set the ``:compressors`` option.
Set this option ``false`` to silence the warning.
- ``true``, ``false``
- none
* - ``:connect``
- **Deprecated.** Disables deployment topology discovery normally
performed by the dirver and forces the cluster topology to a specific
type. Valid values are ``:direct``, ``:load_balanced``,
``:replica_set`` or ``:sharded``. If ``:load_balanced`` is used,
the client will behave as if it is connected to a load balancer
regardless of whether the server(s) it connects to advertise themselves
as load balancers.
- ``Symbol``
- none
* - ``:connect_timeout``
- The number of seconds to wait to establish a socket connection
before raising an exception. This timeout is also used for SRV DNS
record resolution. ``nil`` and ``0`` mean no timeout.
Client creation will fail with an error if an invalid timeout value
is passed (such as a negative value or a non-numeric value).
- ``Float``
- 10
* - ``:database``
- The name of the database to connect to.
- ``String``
- admin
* - ``:direct_connection``
- Connect directly to the specified host, do not discover deployment
topology.
- ``Boolean``
- false
* - ``:heartbeat_frequency``
- The number of seconds for the server monitors to refresh
server states asynchronously.
- ``Float``
- 10
* - ``:id_generator``
- A custom object to generate ids for documents. Must respond to #generate.
- ``Object``
- none
* - ``:load_balanced``
- Whether to expect to connect to a load balancer.
- ``Boolean``
- false
* - ``:local_threshold``
- Specifies the maximum latency in seconds between the nearest
server and the servers that can be available for selection to operate on.
- ``Float``
- 0.015
* - ``:logger``
- A custom logger.
- ``Object``
- ``Logger``
* - ``:max_connecting``
- The maximum number of connections that the connection pool will try to establish in parallel.
- ``Integer``
- 2
* - ``:max_idle_time``
- The maximum time, in seconds, that a connection can be idle before it
is closed by the connection pool.
*Warning:* when connected to a load balancer, the driver uses existing
connections for iterating cursors (which includes change streams)
and executing transactions. Setting an idle time via this option may
cause the driver to close connections that are needed for subsequent
operations, causing those operations to fail.
- ``Integer``
- none
* - ``:max_pool_size``
- The maximum size of the connection pool for each server.
Setting this option to zero removes the max size limit from the connection pool, permitting it to grow to any number of connections.
- ``Integer``
- 20
* - ``:max_read_retries``
- The maximum number of read retries, when legacy read retries are used.
Set to 0 to disable legacy read retries.
- ``Integer``
- 1
* - ``:max_write_retries``
- The maximum number of write retries, when legacy write retries are used.
Set to 0 to disable legacy write retries.
- ``Integer``
- 1
* - ``:min_pool_size``
- The minimum number of connections in the connection pool for each
server. The driver will establish connections in the background until
the pool contains this many connections.
- ``Integer``
- 0
* - ``:monitoring``
- The monitoring object.
- ``Object``
- none
* - ``:password``
- The password of the user to authenticate with.
- ``String``
- none
* - ``:platform``
- Platform information to include in the metadata printed to the mongod logs upon establishing a
connection in server versions >= 3.4.
- ``String``
- none
* - ``:read``
- Specifies the read preference mode and tag sets for selecting servers
as a ``Hash``. Allowed Keys in the hash are ``:mode``, ``:tag_sets`` and
``:max_staleness``.
.. code-block:: ruby
{ read:
{ mode: :secondary,
tag_sets: [ "data_center" => "berlin" ],
max_staleness: 5,
}
}
If tag sets are provided, they must be an array of hashes. A server
satisfies the read preference if its tags match any one hash in the
provided tag sets.
Each tag set must be a hash, and will be converted internally to
a ``BSON::Document`` instance prior to being used for server selection.
Hash keys can be strings or symbols. The keys are case sensitive.
Hash values must be strings, and are matched exactly against the values
in the replica set configuration.
- ``Hash``
- ``{ :mode => :primary }``
* - ``:read_concern``
- Specifies the read concern options. The only valid key is ``level``,
for which the valid values are ``:local``, ``:majority``, and
``:snapshot``.
- ``Hash``
- none
* - ``:read_retry_interval``
- The interval, in seconds, in which reads on a mongos are retried.
- ``Integer``
- 5
* - ``:replica_set``
- When connecting to a replica set, this is the name of the set to
filter servers by.
- ``String``
- none
* - ``:retry_writes``
- If a single-statement write operation fails from a network error, the driver automatically retries it once
when connected to server versions 3.6+.
- ``Boolean``
- true
* - ``:sdam_proc``
- Since the client begins monitoring the deployment in background as
soon as it is constructed, constructing a client and then subscribing
to `SDAM <sdam>`_ events in a separate statement may result in the
subscriber not receiving some of the SDAM events. The ``:sdam_proc``
option permits adding event subscribers on the client being constructed
before any SDAM events are published.
Pass a ``Proc`` which will be called with the ``Client`` as the argument
after the client's event subscription mechanism has been initialized
but before any of the servers are added to the client. Use this
``Proc`` to set up SDAM event subscribers on the client.
Note: the client is not fully constructed when the ``Proc`` provided in
``:sdam_proc is invoked, in particular the cluster is nil at this time.
``:sdam_proc`` procedure should limit itself to calling
``Client#subscribe`` and ``Client#unsubscribe`` methods on on the
passed client only.
- ``Proc``
- none
* - ``:server_api``
- The server API version requested.
This is a hash with the following allowed items:
- ``:version`` (String)
- ``:strict`` (true or false)
- ``:deprecation_errors`` (true or false)
Note that the server API version can only be specified as a Ruby option,
not as a URI option, and it cannot be overridden for database and
collection objects.
If server API version is changed on a client (such as via the ``with``
call), the entire API version hash is replaced with the new specification
(the old and the new individual fields are NOT merged).
- ``Hash``
- none
* - ``:server_selection_timeout``
- The number of seconds to wait for an appropriate server to
be selected for an operation to be executed before raising an exception.
- ``Float``
- 30
* - ``:socket_timeout``
- The number of seconds to wait for an operation to execute on a
socket before raising an exception. ``nil`` and ``0`` mean no timeout.
Client creation will fail with an error if an invalid timeout value
is passed (such as a negative value or a non-numeric value).
- ``Float``
- none
* - ``:srv_max_hosts``
- The maximum number of mongoses that the driver will communicate with
for sharded topologies. If this option is set to 0, there will
be no maximum number of mongoses. If the given URI resolves
to more hosts than ``:srv_max_hosts``, the client will ramdomly
choose an ``:srv_max_hosts`` sized subset of hosts. Note that the
hosts that the driver ignores during client construction will never
be used. If the hosts chosen by the driver become unavailable, the
client will quit working completely, even though the deployment has
other functional mongoses.
- ``Integer``
- 0
* - ``:srv_service_name``
- The service name to use in the SRV DNS query.
- ``String``
- mongodb
* - ``:ssl``
- Tell the client to connect to the servers via TLS.
- ``Boolean``
- false
* - ``:ssl_ca_cert``
- The file path containing concatenated certificate authority certificates
used to validate certs passed from the other end of the connection.
One of ``:ssl_ca_cert``, ``:ssl_ca_cert_string`` or ``:ssl_ca_cert_object``
(in order of priority) is required for ``:ssl_verify``.
- ``String``
- none
* - ``:ssl_ca_cert_object``
- An array of OpenSSL::X509::Certificate representing the certificate
authority certificates used to validate certs passed from the other end
of the connection. One of ``:ssl_ca_cert``, ``:ssl_ca_cert_string`` or
``:ssl_ca_cert_object`` (in order of priority) is required for ``:ssl_verify``.
- ``Array< OpenSSL::X509::Certificate >``
- none
* - ``:ssl_ca_cert_string``
- A string containing concatenated certificate authority certificates
used to validate certs passed from the other end of the connection.
One of ``:ssl_ca_cert``, ``:ssl_ca_cert_string`` or ``:ssl_ca_cert_object``
(in order of priority) is required for ``:ssl_verify``.
- ``String``
- none
* - ``:ssl_cert``
- Path to the client certificate file used to identify the application to
the MongoDB servers. The file may also contain the certificate's private
key; if so, the private key is ignored by this option. The file may
also contain intermediate certificates forming the certificate chain
from the client certificate to the CA certificate; any intermediate
certificates will be parsed by the driver and provided to the OpenSSL
context in ``extra_chain_cert`` attribute. If intermediate certificates
are provided, they must follow the client certificate which must be
the first certificate in the file.
This option, if present, takes precedence over ``:ssl_cert_string`` and
``:ssl_cert_object`` options.
- ``String``
- none
* - ``:ssl_cert_object``
- The OpenSSL::X509::Certificate used to identify the application to
the MongoDB servers. Only one certificate may be passed through this
option.
- ``OpenSSL::X509::Certificate``
- none
* - ``:ssl_cert_string``
- A string containing the PEM-encoded certificate used to identify the
application to the MongoDB servers. The string may also contain the
certificate's private key; if so, the private key is ignored by this
option. The string may also contain intermediate certificates forming
the certificate chain from the client certificate to the CA certificate;
any intermediate certificates will be parsed by the driver and provided
to the OpenSSL context in ``extra_chain_cert`` attribute. If intermediate
certificates are provided, they must follow the client certificate which
must be the first certificatet in the string.
This option, if present, takes precedence over the ``:ssl_cert_object``
option.
- ``String``
- none
* - ``:ssl_key``
- The private keyfile used to identify the connection against MongoDB. Note that even if the key is stored in
the same file as the certificate, both need to be explicitly specified. This option, if present, takes
precedence over the values of :ssl_key_string and :ssl_key_object.
- ``String``
- none
* - ``:ssl_key_object``
- The private key used to identify the connection against MongoDB.
- ``OpenSSL::PKey``
- none
* - ``:ssl_key_pass_phrase``
- A passphrase for the private key.
- ``String``
- none
* - ``:ssl_key_string``
- A string containing the PEM-encoded private key used to identify the
connection against MongoDB. This parameter, if present, takes precedence
over the value of option :ssl_key_object.
- ``String``
- none
* - ``:ssl_verify``
- Whether to perform peer certificate, hostname and OCSP endpoint
validation. Note that the decision of whether to validate certificates
will be overridden if ``:ssl_verify_certificate`` is set, the decision
of whether to validate hostnames will be overridden if
``:ssl_verify_hostname`` is set and the decision of whether to validate
OCSP endpoint will be overridden if ``:ssl_verify_ocsp_endpoint`` is set.
- ``Boolean``
- true
* - ``:ssl_verify_certificate``
- Whether to perform peer certificate validation. This setting overrides
the ``:ssl_verify`` setting with respect to whether certificate
validation is performed.
- ``Boolean``
- true
* - ``:ssl_verify_hostname``
- Whether to perform peer hostname validation. This setting overrides
the ``:ssl_verify`` setting with respect to whether hostname validation
is performed.
- ``Boolean``
- true
* - ``:ssl_verify_ocsp_endpoint``
- Whether to validate server-supplied certificate against the OCSP
endpoint specified in the certificate, if the OCSP endpoint is specified
in the certificate. This setting overrides :ssl_verify with respect to
whether OCSP endpoint validation is performed.
- ``Boolean``
- true
* - ``:truncate_logs``
- Whether to truncate the logs at the default 250 characters.
- ``Boolean``
- true
* - ``:user``
- The name of the user to authenticate with.
- ``String``
- none
* - ``:wait_queue_timeout``
- The number of seconds to wait for a connection in the connection
pool to become available.
- ``Float``
- 10
* - ``:wrapping_libraries``
- Information about libraries such as ODMs that are wrapping the driver.
Specify the lower level libraries first. Allowed hash keys: :name,
:version, :platform. Example: ``[name: 'Mongoid', version: '7.1.2']``
- ``Array<Hash>``
- none
* - ``:write``
- Deprecated. Equivalent to ``:write_concern`` option. If both ``:write``
and ``:write_concern`` are specified, their values must be identical.
- ``Hash``
- ``{ w: 1 }``
* - ``:write_concern``
- Specifies write concern options as a ``Hash``.
Keys in the hash can be ``:w``, ``:wtimeout``, ``:j``, ``:fsync``.
Note that ``:wtimeout`` is specified in milliseconds, not seconds.
.. code-block:: ruby
{ write_concern: { w: 2 } }
- ``Hash``
- ``{ w: 1 }``
* - ``:zlib_compression_level``
- The Zlib compression level to use, if using compression. See Ruby's Zlib module for valid levels.
- ``Integer``
- none
.. note::
The Ruby driver does not implement certificate revocation list (CRL)
checking.
URI Options
-----------
Since the URI options are required to be in camel case, which is not the Ruby
standard, the following table shows URI options and their corresponding Ruby
options.
URI options are explained in detail in the :manual:`Connection URI reference
</reference/connection-string/>`.
.. note::
Options that are set in **milliseconds** in the URI are
represented as a ``float`` in Ruby and the units are **seconds**.
.. list-table::
:header-rows: 1
:widths: 40 105
* - URI Option
- Ruby Option
* - appName=String
- ``:app_name => String``
* - authMechanism=String
- ``:auth_mech => Symbol``
Auth mechanism values are converted as follows from URI options to
Ruby options:
- ``GSSAPI`` => ``:gssapi``
- ``MONGODB-CR`` => ``:mongodb_cr``
- ``MONGODB-X509`` => ``:mongodb_x509``
- ``PLAIN`` => ``:plain``
- ``SCRAM-SHA-1`` => ``:scram``
- ``SCRAM-SHA-256`` => ``:scram256``
If a different value is provided for auth mechanism, it is converted
to the Ruby option unmodified and retains its ``String`` type.
Note that, while currently the driver allows a ``Client`` instance
to be constructed with an unrecognized auth mechanism, this behavior
`may change in a future version of the driver <https://jira.mongodb.org/browse/RUBY-1745>`_.
* - authMechanismProperties=Strings
- ``{ :auth_mech_properties => { :service_realm => String, :canonicalize_host_name => true|false, :service_name => String } }``
Specified as comma-separated key:value pairs, e.g. ``"SERVICE_REALM:foo,CANONICALIZE_HOST_NAME:TRUE"``.
* - authSource=String
- ``:auth_source => String``
* - compressors=Strings
- ``:compressors => Array<String>``
A comma-separated list of potential compressors to use, in order of
preference. Please see below for details on how the driver implements
compression.
* - connect=String
- ``:connect => Symbol``