-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmongo_client.py
2769 lines (2411 loc) · 119 KB
/
mongo_client.py
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
# Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
"""Tools for connecting to MongoDB.
.. seealso:: :doc:`/examples/high_availability` for examples of connecting
to replica sets or sets of mongos servers.
To get a :class:`~pymongo.asynchronous.database.AsyncDatabase` instance from a
:class:`AsyncMongoClient` use either dictionary-style or attribute-style
access:
.. doctest::
>>> from pymongo import AsyncMongoClient
>>> c = AsyncMongoClient()
>>> c.test_database
AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database')
>>> c["test-database"]
AsyncDatabase(AsyncMongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test-database')
"""
from __future__ import annotations
import asyncio
import contextlib
import os
import warnings
import weakref
from collections import defaultdict
from typing import (
TYPE_CHECKING,
Any,
AsyncContextManager,
AsyncGenerator,
Callable,
Coroutine,
FrozenSet,
Generic,
Mapping,
MutableMapping,
NoReturn,
Optional,
Sequence,
Type,
TypeVar,
Union,
cast,
)
from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, TypeRegistry
from bson.timestamp import Timestamp
from pymongo import _csot, common, helpers_shared, periodic_executor, uri_parser
from pymongo.asynchronous import client_session, database
from pymongo.asynchronous.change_stream import AsyncChangeStream, AsyncClusterChangeStream
from pymongo.asynchronous.client_bulk import _AsyncClientBulk
from pymongo.asynchronous.client_session import _EmptyServerSession
from pymongo.asynchronous.command_cursor import AsyncCommandCursor
from pymongo.asynchronous.settings import TopologySettings
from pymongo.asynchronous.topology import Topology, _ErrorContext
from pymongo.client_options import ClientOptions
from pymongo.errors import (
AutoReconnect,
BulkWriteError,
ClientBulkWriteException,
ConfigurationError,
ConnectionFailure,
InvalidOperation,
NotPrimaryError,
OperationFailure,
PyMongoError,
ServerSelectionTimeoutError,
WaitQueueTimeoutError,
WriteConcernError,
)
from pymongo.lock import (
_HAS_REGISTER_AT_FORK,
_async_create_lock,
_release_locks,
)
from pymongo.logger import _CLIENT_LOGGER, _log_client_error, _log_or_warn
from pymongo.message import _CursorAddress, _GetMore, _Query
from pymongo.monitoring import ConnectionClosedReason
from pymongo.operations import (
DeleteMany,
DeleteOne,
InsertOne,
ReplaceOne,
UpdateMany,
UpdateOne,
_Op,
)
from pymongo.read_preferences import ReadPreference, _ServerMode
from pymongo.results import ClientBulkWriteResult
from pymongo.server_selectors import writable_server_selector
from pymongo.server_type import SERVER_TYPE
from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription
from pymongo.typings import (
ClusterTime,
_Address,
_CollationIn,
_DocumentType,
_DocumentTypeArg,
_Pipeline,
)
from pymongo.uri_parser import (
_check_options,
_handle_option_deprecations,
_handle_security_options,
_normalize_options,
)
from pymongo.write_concern import DEFAULT_WRITE_CONCERN, WriteConcern
if TYPE_CHECKING:
from types import TracebackType
from bson.objectid import ObjectId
from pymongo.asynchronous.bulk import _AsyncBulk
from pymongo.asynchronous.client_session import AsyncClientSession, _ServerSession
from pymongo.asynchronous.cursor import _ConnectionManager
from pymongo.asynchronous.pool import AsyncConnection
from pymongo.asynchronous.server import Server
from pymongo.read_concern import ReadConcern
from pymongo.response import Response
from pymongo.server_selectors import Selection
T = TypeVar("T")
_WriteCall = Callable[
[Optional["AsyncClientSession"], "AsyncConnection", bool], Coroutine[Any, Any, T]
]
_ReadCall = Callable[
[Optional["AsyncClientSession"], "Server", "AsyncConnection", _ServerMode],
Coroutine[Any, Any, T],
]
_IS_SYNC = False
_WriteOp = Union[
InsertOne,
DeleteOne,
DeleteMany,
ReplaceOne,
UpdateOne,
UpdateMany,
]
class AsyncMongoClient(common.BaseObject, Generic[_DocumentType]):
HOST = "localhost"
PORT = 27017
# Define order to retrieve options from ClientOptions for __repr__.
# No host/port; these are retrieved from TopologySettings.
_constructor_args = ("document_class", "tz_aware", "connect")
_clients: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
def __init__(
self,
host: Optional[Union[str, Sequence[str]]] = None,
port: Optional[int] = None,
document_class: Optional[Type[_DocumentType]] = None,
tz_aware: Optional[bool] = None,
connect: Optional[bool] = None,
type_registry: Optional[TypeRegistry] = None,
**kwargs: Any,
) -> None:
"""Client for a MongoDB instance, a replica set, or a set of mongoses.
.. warning:: Starting in PyMongo 4.0, ``directConnection`` now has a default value of
False instead of None.
For more details, see the relevant section of the PyMongo 4.x migration guide:
:ref:`pymongo4-migration-direct-connection`.
.. warning:: This API is currently in beta, meaning the classes, methods, and behaviors described within may change before the full release.
The client object is thread-safe and has connection-pooling built in.
If an operation fails because of a network error,
:class:`~pymongo.errors.ConnectionFailure` is raised and the client
reconnects in the background. Application code should handle this
exception (recognizing that the operation failed) and then continue to
execute.
The `host` parameter can be a full `mongodb URI
<http://dochub.mongodb.org/core/connections>`_, in addition to
a simple hostname. It can also be a list of hostnames but no more
than one URI. Any port specified in the host string(s) will override
the `port` parameter. For username and
passwords reserved characters like ':', '/', '+' and '@' must be
percent encoded following RFC 2396::
from urllib.parse import quote_plus
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), host)
client = AsyncMongoClient(uri)
Unix domain sockets are also supported. The socket path must be percent
encoded in the URI::
uri = "mongodb://%s:%s@%s" % (
quote_plus(user), quote_plus(password), quote_plus(socket_path))
client = AsyncMongoClient(uri)
But not when passed as a simple hostname::
client = AsyncMongoClient('/tmp/mongodb-27017.sock')
Starting with version 3.6, PyMongo supports mongodb+srv:// URIs. The
URI must include one, and only one, hostname. The hostname will be
resolved to one or more DNS `SRV records
<https://en.wikipedia.org/wiki/SRV_record>`_ which will be used
as the seed list for connecting to the MongoDB deployment. When using
SRV URIs, the `authSource` and `replicaSet` configuration options can
be specified using `TXT records
<https://en.wikipedia.org/wiki/TXT_record>`_. See the
`Initial DNS Seedlist Discovery spec
<https://github.com/mongodb/specifications/blob/master/source/
initial-dns-seedlist-discovery/initial-dns-seedlist-discovery.md>`_
for more details. Note that the use of SRV URIs implicitly enables
TLS support. Pass tls=false in the URI to override.
.. note:: AsyncMongoClient creation will block waiting for answers from
DNS when mongodb+srv:// URIs are used.
.. note:: Starting with version 3.0 the :class:`AsyncMongoClient`
constructor no longer blocks while connecting to the server or
servers, and it no longer raises
:class:`~pymongo.errors.ConnectionFailure` if they are
unavailable, nor :class:`~pymongo.errors.ConfigurationError`
if the user's credentials are wrong. Instead, the constructor
returns immediately and launches the connection process on
background threads. You can check if the server is available
like this::
from pymongo.errors import ConnectionFailure
client = AsyncMongoClient()
try:
# The ping command is cheap and does not require auth.
client.admin.command('ping')
except ConnectionFailure:
print("Server not available")
.. warning:: When using PyMongo in a multiprocessing context, please
read :ref:`multiprocessing` first.
.. note:: Many of the following options can be passed using a MongoDB
URI or keyword parameters. If the same option is passed in a URI and
as a keyword parameter the keyword parameter takes precedence.
:param host: hostname or IP address or Unix domain socket
path of a single mongod or mongos instance to connect to, or a
mongodb URI, or a list of hostnames (but no more than one mongodb
URI). If `host` is an IPv6 literal it must be enclosed in '['
and ']' characters
following the RFC2732 URL syntax (e.g. '[::1]' for localhost).
Multihomed and round robin DNS addresses are **not** supported.
:param port: port number on which to connect
:param document_class: default class to use for
documents returned from queries on this client
:param tz_aware: if ``True``,
:class:`~datetime.datetime` instances returned as values
in a document by this :class:`AsyncMongoClient` will be timezone
aware (otherwise they will be naive)
:param connect: **Not supported by AsyncMongoClient**.
:param type_registry: instance of
:class:`~bson.codec_options.TypeRegistry` to enable encoding
and decoding of custom types.
:param kwargs: **Additional optional parameters available as keyword arguments:**
- `datetime_conversion` (optional): Specifies how UTC datetimes should be decoded
within BSON. Valid options include 'datetime_ms' to return as a
DatetimeMS, 'datetime' to return as a datetime.datetime and
raising a ValueError for out-of-range values, 'datetime_auto' to
return DatetimeMS objects when the underlying datetime is
out-of-range and 'datetime_clamp' to clamp to the minimum and
maximum possible datetimes. Defaults to 'datetime'. See
:ref:`handling-out-of-range-datetimes` for details.
- `directConnection` (optional): if ``True``, forces this client to
connect directly to the specified MongoDB host as a standalone.
If ``false``, the client connects to the entire replica set of
which the given MongoDB host(s) is a part. If this is ``True``
and a mongodb+srv:// URI or a URI containing multiple seeds is
provided, an exception will be raised.
- `maxPoolSize` (optional): The maximum allowable number of
concurrent connections to each connected server. Requests to a
server will block if there are `maxPoolSize` outstanding
connections to the requested server. Defaults to 100. Can be
either 0 or None, in which case there is no limit on the number
of concurrent connections.
- `minPoolSize` (optional): The minimum required number of concurrent
connections that the pool will maintain to each connected server.
Default is 0.
- `maxIdleTimeMS` (optional): The maximum number of milliseconds that
a connection can remain idle in the pool before being removed and
replaced. Defaults to `None` (no limit).
- `maxConnecting` (optional): The maximum number of connections that
each pool can establish concurrently. Defaults to `2`.
- `timeoutMS`: (integer or None) Controls how long (in
milliseconds) the driver will wait when executing an operation
(including retry attempts) before raising a timeout error.
``0`` or ``None`` means no timeout.
- `socketTimeoutMS`: (integer or None) Controls how long (in
milliseconds) the driver will wait for a response after sending an
ordinary (non-monitoring) database operation before concluding that
a network error has occurred. ``0`` or ``None`` means no timeout.
Defaults to ``None`` (no timeout).
- `connectTimeoutMS`: (integer or None) Controls how long (in
milliseconds) the driver will wait during server monitoring when
connecting a new socket to a server before concluding the server
is unavailable. ``0`` or ``None`` means no timeout.
Defaults to ``20000`` (20 seconds).
- `server_selector`: (callable or None) Optional, user-provided
function that augments server selection rules. The function should
accept as an argument a list of
:class:`~pymongo.server_description.ServerDescription` objects and
return a list of server descriptions that should be considered
suitable for the desired operation.
- `serverSelectionTimeoutMS`: (integer) Controls how long (in
milliseconds) the driver will wait to find an available,
appropriate server to carry out a database operation; while it is
waiting, multiple server monitoring operations may be carried out,
each controlled by `connectTimeoutMS`. Defaults to ``30000`` (30
seconds).
- `waitQueueTimeoutMS`: (integer or None) How long (in milliseconds)
a thread will wait for a socket from the pool if the pool has no
free sockets. Defaults to ``None`` (no timeout).
- `heartbeatFrequencyMS`: (optional) The number of milliseconds
between periodic server checks, or None to accept the default
frequency of 10 seconds.
- `serverMonitoringMode`: (optional) The server monitoring mode to use.
Valid values are the strings: "auto", "stream", "poll". Defaults to "auto".
- `appname`: (string or None) The name of the application that
created this AsyncMongoClient instance. The server will log this value
upon establishing each connection. It is also recorded in the slow
query log and profile collections.
- `driver`: (pair or None) A driver implemented on top of PyMongo can
pass a :class:`~pymongo.driver_info.DriverInfo` to add its name,
version, and platform to the message printed in the server log when
establishing a connection.
- `event_listeners`: a list or tuple of event listeners. See
:mod:`~pymongo.monitoring` for details.
- `retryWrites`: (boolean) Whether supported write operations
executed within this AsyncMongoClient will be retried once after a
network error. Defaults to ``True``.
The supported write operations are:
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, as long as
:class:`~pymongo.asynchronous.operations.UpdateMany` or
:class:`~pymongo.asynchronous.operations.DeleteMany` are not included.
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.delete_one`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_one`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.insert_many`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.replace_one`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.update_one`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_delete`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_replace`
- :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_update`
Unsupported write operations include, but are not limited to,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` using the ``$out``
pipeline operator and any operation with an unacknowledged write
concern (e.g. {w: 0})). See
https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.md
- `retryReads`: (boolean) Whether supported read operations
executed within this AsyncMongoClient will be retried once after a
network error. Defaults to ``True``.
The supported read operations are:
:meth:`~pymongo.asynchronous.collection.AsyncCollection.find`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` without ``$out``,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.distinct`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.count`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.estimated_document_count`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.count_documents`,
:meth:`pymongo.asynchronous.collection.AsyncCollection.watch`,
:meth:`~pymongo.asynchronous.collection.AsyncCollection.list_indexes`,
:meth:`pymongo.asynchronous.database.AsyncDatabase.watch`,
:meth:`~pymongo.asynchronous.database.AsyncDatabase.list_collections`,
:meth:`pymongo.asynchronous.mongo_client.AsyncMongoClient.watch`,
and :meth:`~pymongo.asynchronous.mongo_client.AsyncMongoClient.list_databases`.
Unsupported read operations include, but are not limited to
:meth:`~pymongo.asynchronous.database.AsyncDatabase.command` and any getMore
operation on a cursor.
Enabling retryable reads makes applications more resilient to
transient errors such as network failures, database upgrades, and
replica set failovers. For an exact definition of which errors
trigger a retry, see the `retryable reads specification
<https://github.com/mongodb/specifications/blob/master/source/retryable-reads/retryable-reads.md>`_.
- `compressors`: Comma separated list of compressors for wire
protocol compression. The list is used to negotiate a compressor
with the server. Currently supported options are "snappy", "zlib"
and "zstd". Support for snappy requires the
`python-snappy <https://pypi.org/project/python-snappy/>`_ package.
zlib support requires the Python standard library zlib module. zstd
requires the `zstandard <https://pypi.org/project/zstandard/>`_
package. By default no compression is used. Compression support
must also be enabled on the server. MongoDB 3.6+ supports snappy
and zlib compression. MongoDB 4.2+ adds support for zstd.
See :ref:`network-compression-example` for details.
- `zlibCompressionLevel`: (int) The zlib compression level to use
when zlib is used as the wire protocol compressor. Supported values
are -1 through 9. -1 tells the zlib library to use its default
compression level (usually 6). 0 means no compression. 1 is best
speed. 9 is best compression. Defaults to -1.
- `uuidRepresentation`: The BSON representation to use when encoding
from and decoding to instances of :class:`~uuid.UUID`. Valid
values are the strings: "standard", "pythonLegacy", "javaLegacy",
"csharpLegacy", and "unspecified" (the default). New applications
should consider setting this to "standard" for cross language
compatibility. See :ref:`handling-uuid-data-example` for details.
- `unicode_decode_error_handler`: The error handler to apply when
a Unicode-related error occurs during BSON decoding that would
otherwise raise :exc:`UnicodeDecodeError`. Valid options include
'strict', 'replace', 'backslashreplace', 'surrogateescape', and
'ignore'. Defaults to 'strict'.
- `srvServiceName`: (string) The SRV service name to use for
"mongodb+srv://" URIs. Defaults to "mongodb". Use it like so::
AsyncMongoClient("mongodb+srv://example.com/?srvServiceName=customname")
- `srvMaxHosts`: (int) limits the number of mongos-like hosts a client will
connect to. More specifically, when a "mongodb+srv://" connection string
resolves to more than srvMaxHosts number of hosts, the client will randomly
choose an srvMaxHosts sized subset of hosts.
| **Write Concern options:**
| (Only set if passed. No default values.)
- `w`: (integer or string) If this is a replica set, write operations
will block until they have been replicated to the specified number
or tagged set of servers. `w=<int>` always includes the replica set
primary (e.g. w=3 means write to the primary and wait until
replicated to **two** secondaries). Passing w=0 **disables write
acknowledgement** and all other write concern options.
- `wTimeoutMS`: **DEPRECATED** (integer) Used in conjunction with `w`.
Specify a value in milliseconds to control how long to wait for write propagation
to complete. If replication does not complete in the given
timeframe, a timeout exception is raised. Passing wTimeoutMS=0
will cause **write operations to wait indefinitely**.
- `journal`: If ``True`` block until write operations have been
committed to the journal. Cannot be used in combination with
`fsync`. Write operations will fail with an exception if this
option is used when the server is running without journaling.
- `fsync`: If ``True`` and the server is running without journaling,
blocks until the server has synced all data files to disk. If the
server is running with journaling, this acts the same as the `j`
option, blocking until write operations have been committed to the
journal. Cannot be used in combination with `j`.
| **Replica set keyword arguments for connecting with a replica set
- either directly or via a mongos:**
- `replicaSet`: (string or None) The name of the replica set to
connect to. The driver will verify that all servers it connects to
match this name. Implies that the hosts specified are a seed list
and the driver should attempt to find all members of the set.
Defaults to ``None``.
| **Read Preference:**
- `readPreference`: The replica set read preference for this client.
One of ``primary``, ``primaryPreferred``, ``secondary``,
``secondaryPreferred``, or ``nearest``. Defaults to ``primary``.
- `readPreferenceTags`: Specifies a tag set as a comma-separated list
of colon-separated key-value pairs. For example ``dc:ny,rack:1``.
Defaults to ``None``.
- `maxStalenessSeconds`: (integer) The maximum estimated
length of time a replica set secondary can fall behind the primary
in replication before it will no longer be selected for operations.
Defaults to ``-1``, meaning no maximum. If maxStalenessSeconds
is set, it must be a positive integer greater than or equal to
90 seconds.
.. seealso:: :doc:`/examples/server_selection`
| **Authentication:**
- `username`: A string.
- `password`: A string.
Although username and password must be percent-escaped in a MongoDB
URI, they must not be percent-escaped when passed as parameters. In
this example, both the space and slash special characters are passed
as-is::
AsyncMongoClient(username="user name", password="pass/word")
- `authSource`: The database to authenticate on. Defaults to the
database specified in the URI, if provided, or to "admin".
- `authMechanism`: See :data:`~pymongo.auth.MECHANISMS` for options.
If no mechanism is specified, PyMongo automatically negotiates the
mechanism to use (SCRAM-SHA-1 or SCRAM-SHA-256) with the MongoDB server.
- `authMechanismProperties`: Used to specify authentication mechanism
specific options. To specify the service name for GSSAPI
authentication pass authMechanismProperties='SERVICE_NAME:<service
name>'.
To specify the session token for MONGODB-AWS authentication pass
``authMechanismProperties='AWS_SESSION_TOKEN:<session token>'``.
.. seealso:: :doc:`/examples/authentication`
| **TLS/SSL configuration:**
- `tls`: (boolean) If ``True``, create the connection to the server
using transport layer security. Defaults to ``False``.
- `tlsInsecure`: (boolean) Specify whether TLS constraints should be
relaxed as much as possible. Setting ``tlsInsecure=True`` implies
``tlsAllowInvalidCertificates=True`` and
``tlsAllowInvalidHostnames=True``. Defaults to ``False``. Think
very carefully before setting this to ``True`` as it dramatically
reduces the security of TLS.
- `tlsAllowInvalidCertificates`: (boolean) If ``True``, continues
the TLS handshake regardless of the outcome of the certificate
verification process. If this is ``False``, and a value is not
provided for ``tlsCAFile``, PyMongo will attempt to load system
provided CA certificates. If the python version in use does not
support loading system CA certificates then the ``tlsCAFile``
parameter must point to a file of CA certificates.
``tlsAllowInvalidCertificates=False`` implies ``tls=True``.
Defaults to ``False``. Think very carefully before setting this
to ``True`` as that could make your application vulnerable to
on-path attackers.
- `tlsAllowInvalidHostnames`: (boolean) If ``True``, disables TLS
hostname verification. ``tlsAllowInvalidHostnames=False`` implies
``tls=True``. Defaults to ``False``. Think very carefully before
setting this to ``True`` as that could make your application
vulnerable to on-path attackers.
- `tlsCAFile`: A file containing a single or a bundle of
"certification authority" certificates, which are used to validate
certificates passed from the other end of the connection.
Implies ``tls=True``. Defaults to ``None``.
- `tlsCertificateKeyFile`: A file containing the client certificate
and private key. Implies ``tls=True``. Defaults to ``None``.
- `tlsCRLFile`: A file containing a PEM or DER formatted
certificate revocation list. Implies ``tls=True``. Defaults to
``None``.
- `tlsCertificateKeyFilePassword`: The password or passphrase for
decrypting the private key in ``tlsCertificateKeyFile``. Only
necessary if the private key is encrypted. Defaults to ``None``.
- `tlsDisableOCSPEndpointCheck`: (boolean) If ``True``, disables
certificate revocation status checking via the OCSP responder
specified on the server certificate.
``tlsDisableOCSPEndpointCheck=False`` implies ``tls=True``.
Defaults to ``False``.
- `ssl`: (boolean) Alias for ``tls``.
| **Read Concern options:**
| (If not set explicitly, this will use the server default)
- `readConcernLevel`: (string) The read concern level specifies the
level of isolation for read operations. For example, a read
operation using a read concern level of ``majority`` will only
return data that has been written to a majority of nodes. If the
level is left unspecified, the server default will be used.
| **Client side encryption options:**
| (If not set explicitly, client side encryption will not be enabled.)
- `auto_encryption_opts`: A
:class:`~pymongo.encryption_options.AutoEncryptionOpts` which
configures this client to automatically encrypt collection commands
and automatically decrypt results. See
:ref:`automatic-client-side-encryption` for an example.
If a :class:`AsyncMongoClient` is configured with
``auto_encryption_opts`` and a non-None ``maxPoolSize``, a
separate internal ``AsyncMongoClient`` is created if any of the
following are true:
- A ``key_vault_client`` is not passed to
:class:`~pymongo.encryption_options.AutoEncryptionOpts`
- ``bypass_auto_encrpytion=False`` is passed to
:class:`~pymongo.encryption_options.AutoEncryptionOpts`
| **Stable API options:**
| (If not set explicitly, Stable API will not be enabled.)
- `server_api`: A
:class:`~pymongo.server_api.ServerApi` which configures this
client to use Stable API. See :ref:`versioned-api-ref` for
details.
.. seealso:: The MongoDB documentation on `connections <https://dochub.mongodb.org/core/connections>`_.
.. versionchanged:: 4.5
Added the ``serverMonitoringMode`` keyword argument.
.. versionchanged:: 4.2
Added the ``timeoutMS`` keyword argument.
.. versionchanged:: 4.0
- Removed the fsync, unlock, is_locked, database_names, and
close_cursor methods.
See the :ref:`pymongo4-migration-guide`.
- Removed the ``waitQueueMultiple`` and ``socketKeepAlive``
keyword arguments.
- The default for `uuidRepresentation` was changed from
``pythonLegacy`` to ``unspecified``.
- Added the ``srvServiceName``, ``maxConnecting``, and ``srvMaxHosts`` URI and
keyword arguments.
.. versionchanged:: 3.12
Added the ``server_api`` keyword argument.
The following keyword arguments were deprecated:
- ``ssl_certfile`` and ``ssl_keyfile`` were deprecated in favor
of ``tlsCertificateKeyFile``.
.. versionchanged:: 3.11
Added the following keyword arguments and URI options:
- ``tlsDisableOCSPEndpointCheck``
- ``directConnection``
.. versionchanged:: 3.9
Added the ``retryReads`` keyword argument and URI option.
Added the ``tlsInsecure`` keyword argument and URI option.
The following keyword arguments and URI options were deprecated:
- ``wTimeout`` was deprecated in favor of ``wTimeoutMS``.
- ``j`` was deprecated in favor of ``journal``.
- ``ssl_cert_reqs`` was deprecated in favor of
``tlsAllowInvalidCertificates``.
- ``ssl_match_hostname`` was deprecated in favor of
``tlsAllowInvalidHostnames``.
- ``ssl_ca_certs`` was deprecated in favor of ``tlsCAFile``.
- ``ssl_certfile`` was deprecated in favor of
``tlsCertificateKeyFile``.
- ``ssl_crlfile`` was deprecated in favor of ``tlsCRLFile``.
- ``ssl_pem_passphrase`` was deprecated in favor of
``tlsCertificateKeyFilePassword``.
.. versionchanged:: 3.9
``retryWrites`` now defaults to ``True``.
.. versionchanged:: 3.8
Added the ``server_selector`` keyword argument.
Added the ``type_registry`` keyword argument.
.. versionchanged:: 3.7
Added the ``driver`` keyword argument.
.. versionchanged:: 3.6
Added support for mongodb+srv:// URIs.
Added the ``retryWrites`` keyword argument and URI option.
.. versionchanged:: 3.5
Add ``username`` and ``password`` options. Document the
``authSource``, ``authMechanism``, and ``authMechanismProperties``
options.
Deprecated the ``socketKeepAlive`` keyword argument and URI option.
``socketKeepAlive`` now defaults to ``True``.
.. versionchanged:: 3.0
:class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` is now the one and only
client class for a standalone server, mongos, or replica set.
It includes the functionality that had been split into
:class:`~pymongo.asynchronous.mongo_client.MongoReplicaSetClient`: it can connect
to a replica set, discover all its members, and monitor the set for
stepdowns, elections, and reconfigs.
The :class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` constructor no
longer blocks while connecting to the server or servers, and it no
longer raises :class:`~pymongo.errors.ConnectionFailure` if they
are unavailable, nor :class:`~pymongo.errors.ConfigurationError`
if the user's credentials are wrong. Instead, the constructor
returns immediately and launches the connection process on
background threads.
Therefore the ``alive`` method is removed since it no longer
provides meaningful information; even if the client is disconnected,
it may discover a server in time to fulfill the next operation.
In PyMongo 2.x, :class:`~pymongo.asynchronous.AsyncMongoClient` accepted a list of
standalone MongoDB servers and used the first it could connect to::
AsyncMongoClient(['host1.com:27017', 'host2.com:27017'])
A list of multiple standalones is no longer supported; if multiple
servers are listed they must be members of the same replica set, or
mongoses in the same sharded cluster.
The behavior for a list of mongoses is changed from "high
availability" to "load balancing". Before, the client connected to
the lowest-latency mongos in the list, and used it until a network
error prompted it to re-evaluate all mongoses' latencies and
reconnect to one of them. In PyMongo 3, the client monitors its
network latency to all the mongoses continuously, and distributes
operations evenly among those with the lowest latency. See
:ref:`mongos-load-balancing` for more information.
The ``connect`` option is added.
The ``start_request``, ``in_request``, and ``end_request`` methods
are removed, as well as the ``auto_start_request`` option.
The ``copy_database`` method is removed, see the
:doc:`copy_database examples </examples/copydb>` for alternatives.
The :meth:`AsyncMongoClient.disconnect` method is removed; it was a
synonym for :meth:`~pymongo.asynchronous.AsyncMongoClient.close`.
:class:`~pymongo.asynchronous.mongo_client.AsyncMongoClient` no longer returns an
instance of :class:`~pymongo.asynchronous.database.AsyncDatabase` for attribute names
with leading underscores. You must use dict-style lookups instead::
client['__my_database__']
Not::
client.__my_database__
.. versionchanged:: 4.7
Deprecated parameter ``wTimeoutMS``, use :meth:`~pymongo.timeout`.
.. versionchanged:: 4.9
The default value of ``connect`` is changed to ``False`` when running in a
Function-as-a-service environment.
"""
doc_class = document_class or dict
self._init_kwargs: dict[str, Any] = {
"host": host,
"port": port,
"document_class": doc_class,
"tz_aware": tz_aware,
"connect": connect,
"type_registry": type_registry,
**kwargs,
}
if host is None:
host = self.HOST
if isinstance(host, str):
host = [host]
if port is None:
port = self.PORT
if not isinstance(port, int):
raise TypeError(f"port must be an instance of int, not {type(port)}")
# _pool_class, _monitor_class, and _condition_class are for deep
# customization of PyMongo, e.g. Motor.
pool_class = kwargs.pop("_pool_class", None)
monitor_class = kwargs.pop("_monitor_class", None)
condition_class = kwargs.pop("_condition_class", None)
# Parse options passed as kwargs.
keyword_opts = common._CaseInsensitiveDictionary(kwargs)
keyword_opts["document_class"] = doc_class
seeds = set()
username = None
password = None
dbase = None
opts = common._CaseInsensitiveDictionary()
fqdn = None
srv_service_name = keyword_opts.get("srvservicename")
srv_max_hosts = keyword_opts.get("srvmaxhosts")
if len([h for h in host if "/" in h]) > 1:
raise ConfigurationError("host must not contain multiple MongoDB URIs")
for entity in host:
# A hostname can only include a-z, 0-9, '-' and '.'. If we find a '/'
# it must be a URI,
# https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names
if "/" in entity:
# Determine connection timeout from kwargs.
timeout = keyword_opts.get("connecttimeoutms")
if timeout is not None:
timeout = common.validate_timeout_or_none_or_zero(
keyword_opts.cased_key("connecttimeoutms"), timeout
)
res = uri_parser.parse_uri(
entity,
port,
validate=True,
warn=True,
normalize=False,
connect_timeout=timeout,
srv_service_name=srv_service_name,
srv_max_hosts=srv_max_hosts,
)
seeds.update(res["nodelist"])
username = res["username"] or username
password = res["password"] or password
dbase = res["database"] or dbase
opts = res["options"]
fqdn = res["fqdn"]
else:
seeds.update(uri_parser.split_hosts(entity, port))
if not seeds:
raise ConfigurationError("need to specify at least one host")
for hostname in [node[0] for node in seeds]:
if _detect_external_db(hostname):
break
# Add options with named keyword arguments to the parsed kwarg options.
if type_registry is not None:
keyword_opts["type_registry"] = type_registry
if tz_aware is None:
tz_aware = opts.get("tz_aware", False)
if connect is None:
# Default to connect=True unless on a FaaS system, which might use fork.
from pymongo.pool_options import _is_faas
connect = opts.get("connect", not _is_faas())
keyword_opts["tz_aware"] = tz_aware
keyword_opts["connect"] = connect
# Handle deprecated options in kwarg options.
keyword_opts = _handle_option_deprecations(keyword_opts)
# Validate kwarg options.
keyword_opts = common._CaseInsensitiveDictionary(
dict(common.validate(keyword_opts.cased_key(k), v) for k, v in keyword_opts.items())
)
# Override connection string options with kwarg options.
opts.update(keyword_opts)
if srv_service_name is None:
srv_service_name = opts.get("srvServiceName", common.SRV_SERVICE_NAME)
srv_max_hosts = srv_max_hosts or opts.get("srvmaxhosts")
# Handle security-option conflicts in combined options.
opts = _handle_security_options(opts)
# Normalize combined options.
opts = _normalize_options(opts)
_check_options(seeds, opts)
# Username and password passed as kwargs override user info in URI.
username = opts.get("username", username)
password = opts.get("password", password)
self._options = options = ClientOptions(username, password, dbase, opts, _IS_SYNC)
self._default_database_name = dbase
self._lock = _async_create_lock()
self._kill_cursors_queue: list = []
self._event_listeners = options.pool_options._event_listeners
super().__init__(
options.codec_options,
options.read_preference,
options.write_concern,
options.read_concern,
)
self._topology_settings = TopologySettings(
seeds=seeds,
replica_set_name=options.replica_set_name,
pool_class=pool_class,
pool_options=options.pool_options,
monitor_class=monitor_class,
condition_class=condition_class,
local_threshold_ms=options.local_threshold_ms,
server_selection_timeout=options.server_selection_timeout,
server_selector=options.server_selector,
heartbeat_frequency=options.heartbeat_frequency,
fqdn=fqdn,
direct_connection=options.direct_connection,
load_balanced=options.load_balanced,
srv_service_name=srv_service_name,
srv_max_hosts=srv_max_hosts,
server_monitoring_mode=options.server_monitoring_mode,
)
self._opened = False
self._closed = False
self._init_background()
if _IS_SYNC and connect:
self._get_topology() # type: ignore[unused-coroutine]
self._encrypter = None
if self._options.auto_encryption_opts:
from pymongo.asynchronous.encryption import _Encrypter
self._encrypter = _Encrypter(self, self._options.auto_encryption_opts)
self._timeout = self._options.timeout
if _HAS_REGISTER_AT_FORK:
# Add this client to the list of weakly referenced items.
# This will be used later if we fork.
AsyncMongoClient._clients[self._topology._topology_id] = self
async def aconnect(self) -> None:
"""Explicitly connect to MongoDB asynchronously instead of on the first operation."""
await self._get_topology()
def _init_background(self, old_pid: Optional[int] = None) -> None:
self._topology = Topology(self._topology_settings)
# Seed the topology with the old one's pid so we can detect clients
# that are opened before a fork and used after.
self._topology._pid = old_pid
async def target() -> bool:
client = self_ref()
if client is None:
return False # Stop the executor.
await AsyncMongoClient._process_periodic_tasks(client)
return True
executor = periodic_executor.AsyncPeriodicExecutor(
interval=common.KILL_CURSOR_FREQUENCY,
min_interval=common.MIN_HEARTBEAT_INTERVAL,
target=target,
name="pymongo_kill_cursors_thread",
)
# We strongly reference the executor and it weakly references us via
# this closure. When the client is freed, stop the executor soon.
self_ref: Any = weakref.ref(self, executor.close)
self._kill_cursors_executor = executor
self._opened = False
def _should_pin_cursor(self, session: Optional[AsyncClientSession]) -> Optional[bool]:
return self._options.load_balanced and not (session and session.in_transaction)
def _after_fork(self) -> None:
"""Resets topology in a child after successfully forking."""
self._init_background(self._topology._pid)
# Reset the session pool to avoid duplicate sessions in the child process.
self._topology._session_pool.reset()
def _duplicate(self, **kwargs: Any) -> AsyncMongoClient:
args = self._init_kwargs.copy()
args.update(kwargs)
return AsyncMongoClient(**args)
async def watch(
self,
pipeline: Optional[_Pipeline] = None,
full_document: Optional[str] = None,
resume_after: Optional[Mapping[str, Any]] = None,
max_await_time_ms: Optional[int] = None,
batch_size: Optional[int] = None,
collation: Optional[_CollationIn] = None,
start_at_operation_time: Optional[Timestamp] = None,
session: Optional[client_session.AsyncClientSession] = None,
start_after: Optional[Mapping[str, Any]] = None,
comment: Optional[Any] = None,
full_document_before_change: Optional[str] = None,
show_expanded_events: Optional[bool] = None,
) -> AsyncChangeStream[_DocumentType]:
"""Watch changes on this cluster.
Performs an aggregation with an implicit initial ``$changeStream``
stage and returns a
:class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` cursor which
iterates over changes on all databases on this cluster.
Introduced in MongoDB 4.0.
.. code-block:: python
with client.watch() as stream:
for change in stream:
print(change)
The :class:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream` iterable
blocks until the next change document is returned or an error is
raised. If the
:meth:`~pymongo.asynchronous.change_stream.AsyncClusterChangeStream.next` method
encounters a network error when retrieving a batch from the server,
it will automatically attempt to recreate the cursor such that no
change events are missed. Any error encountered during the resume
attempt indicates there may be an outage and will be raised.
.. code-block:: python
try:
with client.watch([{"$match": {"operationType": "insert"}}]) as stream:
for insert_change in stream:
print(insert_change)
except pymongo.errors.PyMongoError:
# The AsyncChangeStream encountered an unrecoverable error or the
# resume attempt failed to recreate the cursor.
logging.error("...")
For a precise description of the resume process see the
`change streams specification`_.
:param pipeline: A list of aggregation pipeline stages to
append to an initial ``$changeStream`` stage. Not all
pipeline stages are valid after a ``$changeStream`` stage, see the
MongoDB documentation on change streams for the supported stages.
:param full_document: The fullDocument to pass as an option
to the ``$changeStream`` stage. Allowed values: 'updateLookup',