forked from mongodb/motor
/
core.py
1974 lines (1606 loc) · 70.8 KB
/
core.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 2011-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.
"""Framework-agnostic core of Motor, an asynchronous driver for MongoDB."""
import functools
import time
import warnings
import pymongo
import pymongo.auth
import pymongo.common
import pymongo.database
import pymongo.errors
import pymongo.mongo_client
from pymongo.change_stream import ChangeStream
from pymongo.client_session import ClientSession
from pymongo.collection import Collection
from pymongo.command_cursor import CommandCursor, RawBatchCommandCursor
from pymongo.cursor import _QUERY_OPTIONS, Cursor, RawBatchCursor
from pymongo.database import Database
from pymongo.driver_info import DriverInfo
from pymongo.encryption import ClientEncryption
from . import docstrings
from . import version as motor_version
from .metaprogramming import (
AsyncCommand,
AsyncRead,
AsyncWrite,
DelegateMethod,
MotorCursorChainingMethod,
ReadOnlyProperty,
coroutine_annotation,
create_class_with_framework,
unwrap_args_session,
unwrap_kwargs_session,
)
from .motor_common import callback_type_error
HAS_SSL = True
try:
import ssl
except ImportError:
ssl = None
HAS_SSL = False
# From the Convenient API for Transactions spec, with_transaction must
# halt retries after 120 seconds.
# This limit is non-configurable and was chosen to be twice the 60 second
# default value of MongoDB's `transactionLifetimeLimitSeconds` parameter.
_WITH_TRANSACTION_RETRY_TIME_LIMIT = 120
def _within_time_limit(start_time):
"""Are we within the with_transaction retry limit?"""
return time.monotonic() - start_time < _WITH_TRANSACTION_RETRY_TIME_LIMIT
def _max_time_expired_error(exc):
"""Return true if exc is a MaxTimeMSExpired error."""
return isinstance(exc, pymongo.errors.OperationFailure) and exc.code == 50
class AgnosticBase(object):
def __eq__(self, other):
if (
isinstance(other, self.__class__)
and hasattr(self, "delegate")
and hasattr(other, "delegate")
):
return self.delegate == other.delegate
return NotImplemented
def __init__(self, delegate):
self.delegate = delegate
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self.delegate)
class AgnosticBaseProperties(AgnosticBase):
codec_options = ReadOnlyProperty()
read_preference = ReadOnlyProperty()
read_concern = ReadOnlyProperty()
write_concern = ReadOnlyProperty()
class AgnosticClient(AgnosticBaseProperties):
__motor_class_name__ = "MotorClient"
__delegate_class__ = pymongo.mongo_client.MongoClient
address = ReadOnlyProperty()
arbiters = ReadOnlyProperty()
close = DelegateMethod()
__hash__ = DelegateMethod()
drop_database = AsyncCommand().unwrap("MotorDatabase")
options = ReadOnlyProperty()
get_database = DelegateMethod(doc=docstrings.get_database_doc).wrap(Database)
get_default_database = DelegateMethod(doc=docstrings.get_default_database_doc).wrap(Database)
HOST = ReadOnlyProperty()
is_mongos = ReadOnlyProperty()
is_primary = ReadOnlyProperty()
list_databases = AsyncRead().wrap(CommandCursor)
list_database_names = AsyncRead()
nodes = ReadOnlyProperty()
PORT = ReadOnlyProperty()
primary = ReadOnlyProperty()
read_concern = ReadOnlyProperty()
secondaries = ReadOnlyProperty()
server_info = AsyncRead()
topology_description = ReadOnlyProperty()
start_session = AsyncCommand(doc=docstrings.start_session_doc).wrap(ClientSession)
def __init__(self, *args, **kwargs):
"""Create a new connection to a single MongoDB instance at *host:port*.
Takes the same constructor arguments as
:class:`~pymongo.mongo_client.MongoClient`, as well as:
:Parameters:
- `io_loop` (optional): Special event loop
instance to use instead of default.
"""
if "io_loop" in kwargs:
io_loop = kwargs.pop("io_loop")
self._framework.check_event_loop(io_loop)
else:
io_loop = None
self._io_loop = io_loop
kwargs.setdefault("connect", False)
kwargs.setdefault(
"driver", DriverInfo("Motor", motor_version, self._framework.platform_info())
)
delegate = self.__delegate_class__(*args, **kwargs)
super().__init__(delegate)
@property
def io_loop(self):
if self._io_loop is None:
self._io_loop = self._framework.get_event_loop()
return self._io_loop
def get_io_loop(self):
return self.io_loop
def watch(
self,
pipeline=None,
full_document=None,
resume_after=None,
max_await_time_ms=None,
batch_size=None,
collation=None,
start_at_operation_time=None,
session=None,
start_after=None,
comment=None,
):
"""Watch changes on this cluster.
Returns a :class:`~MotorChangeStream` cursor which iterates over changes
on all databases in this cluster. Introduced in MongoDB 4.0.
See the documentation for :meth:`MotorCollection.watch` for more
details and examples.
:Parameters:
- `pipeline` (optional): 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.
- `full_document` (optional): The fullDocument option to pass
to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
When set to 'updateLookup', the change notification for partial
updates will include both a delta describing the changes to the
document, as well as a copy of the entire document that was
changed from some time after the change occurred.
- `resume_after` (optional): A resume token. If provided, the
change stream will start returning changes that occur directly
after the operation specified in the resume token. A resume token
is the _id value of a change document.
- `max_await_time_ms` (optional): The maximum time in milliseconds
for the server to wait for changes before responding to a getMore
operation.
- `batch_size` (optional): The maximum number of documents to return
per batch.
- `collation` (optional): The :class:`~pymongo.collation.Collation`
to use for the aggregation.
- `start_at_operation_time` (optional): If provided, the resulting
change stream will only return changes that occurred at or after
the specified :class:`~bson.timestamp.Timestamp`. Requires
MongoDB >= 4.0.
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `start_after` (optional): The same as `resume_after` except that
`start_after` can resume notifications after an invalidate event.
This option and `resume_after` are mutually exclusive.
- `comment` (optional): A user-provided comment to attach to this
command.
:Returns:
A :class:`~MotorChangeStream`.
.. versionchanged:: 3.0
Added ``comment`` parameter.
.. versionchanged:: 2.1
Added the ``start_after`` parameter.
.. versionadded:: 2.0
.. mongodoc:: changeStreams
"""
cursor_class = create_class_with_framework(
AgnosticChangeStream, self._framework, self.__module__
)
# Latent cursor that will send initial command on first "async for".
return cursor_class(
self,
pipeline,
full_document,
resume_after,
max_await_time_ms,
batch_size,
collation,
start_at_operation_time,
session,
start_after,
comment,
)
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(
"%s has no attribute %r. To access the %s"
" database, use client['%s']." % (self.__class__.__name__, name, name, name)
)
return self[name]
def __getitem__(self, name):
db_class = create_class_with_framework(AgnosticDatabase, self._framework, self.__module__)
return db_class(self, name)
def wrap(self, obj):
if obj.__class__ == Database:
db_class = create_class_with_framework(
AgnosticDatabase, self._framework, self.__module__
)
return db_class(self, obj.name, _delegate=obj)
elif obj.__class__ == CommandCursor:
command_cursor_class = create_class_with_framework(
AgnosticCommandCursor, self._framework, self.__module__
)
return command_cursor_class(obj, self)
elif obj.__class__ == ClientSession:
session_class = create_class_with_framework(
AgnosticClientSession, self._framework, self.__module__
)
return session_class(obj, self)
class _MotorTransactionContext(object):
"""Internal transaction context manager for start_transaction."""
def __init__(self, session):
self._session = session
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self._session.in_transaction:
if exc_val is None:
await self._session.commit_transaction()
else:
await self._session.abort_transaction()
class AgnosticClientSession(AgnosticBase):
"""A session for ordering sequential operations.
Do not create an instance of :class:`MotorClientSession` directly; use
:meth:`MotorClient.start_session`:
.. code-block:: python3
collection = client.db.collection
async with await client.start_session() as s:
async with s.start_transaction():
await collection.delete_one({'x': 1}, session=s)
await collection.insert_one({'x': 2}, session=s)
.. versionadded:: 2.0
"""
__motor_class_name__ = "MotorClientSession"
__delegate_class__ = ClientSession
commit_transaction = AsyncCommand()
abort_transaction = AsyncCommand()
end_session = AsyncCommand()
cluster_time = ReadOnlyProperty()
has_ended = ReadOnlyProperty()
in_transaction = ReadOnlyProperty()
options = ReadOnlyProperty()
operation_time = ReadOnlyProperty()
session_id = ReadOnlyProperty()
advance_cluster_time = DelegateMethod()
advance_operation_time = DelegateMethod()
def __init__(self, delegate, motor_client):
AgnosticBase.__init__(self, delegate=delegate)
self._client = motor_client
def get_io_loop(self):
return self._client.get_io_loop()
async def with_transaction(
self,
coro,
read_concern=None,
write_concern=None,
read_preference=None,
max_commit_time_ms=None,
):
"""Executes an awaitable in a transaction.
This method starts a transaction on this session, awaits ``coro``
once, and then commits the transaction. For example::
async def coro(session):
orders = session.client.db.orders
inventory = session.client.db.inventory
inserted_id = await orders.insert_one(
{"sku": "abc123", "qty": 100}, session=session)
await inventory.update_one(
{"sku": "abc123", "qty": {"$gte": 100}},
{"$inc": {"qty": -100}}, session=session)
return inserted_id
async with await client.start_session() as session:
inserted_id = await session.with_transaction(coro)
To pass arbitrary arguments to the ``coro``, wrap it with a
``lambda`` like this::
async def coro(session, custom_arg, custom_kwarg=None):
# Transaction operations...
async with await client.start_session() as session:
await session.with_transaction(
lambda s: coro(s, "custom_arg", custom_kwarg=1))
In the event of an exception, ``with_transaction`` may retry the commit
or the entire transaction, therefore ``coro`` may be awaited
multiple times by a single call to ``with_transaction``. Developers
should be mindful of this possiblity when writing a ``coro`` that
modifies application state or has any other side-effects.
Note that even when the ``coro`` is invoked multiple times,
``with_transaction`` ensures that the transaction will be committed
at-most-once on the server.
The ``coro`` should not attempt to start new transactions, but
should simply run operations meant to be contained within a
transaction. The ``coro`` should also not commit the transaction;
this is handled automatically by ``with_transaction``. If the
``coro`` does commit or abort the transaction without error,
however, ``with_transaction`` will return without taking further
action.
When ``coro`` raises an exception, ``with_transaction``
automatically aborts the current transaction. When ``coro`` or
:meth:`~ClientSession.commit_transaction` raises an exception that
includes the ``"TransientTransactionError"`` error label,
``with_transaction`` starts a new transaction and re-executes
the ``coro``.
When :meth:`~ClientSession.commit_transaction` raises an exception with
the ``"UnknownTransactionCommitResult"`` error label,
``with_transaction`` retries the commit until the result of the
transaction is known.
This method will cease retrying after 120 seconds has elapsed. This
timeout is not configurable and any exception raised by the
``coro`` or by :meth:`ClientSession.commit_transaction` after the
timeout is reached will be re-raised. Applications that desire a
different timeout duration should not use this method.
:Parameters:
- `coro`: The coroutine to run inside a transaction. The coroutine must
accept a single argument, this session. Note, under certain error
conditions the coroutine may be run multiple times.
- `read_concern` (optional): The
:class:`~pymongo.read_concern.ReadConcern` to use for this
transaction.
- `write_concern` (optional): The
:class:`~pymongo.write_concern.WriteConcern` to use for this
transaction.
- `read_preference` (optional): The read preference to use for this
transaction. If ``None`` (the default) the :attr:`read_preference`
of this :class:`Database` is used. See
:mod:`~pymongo.read_preferences` for options.
:Returns:
The return value of the ``coro``.
.. versionadded:: 2.1
"""
start_time = time.monotonic()
while True:
async with self.start_transaction(
read_concern, write_concern, read_preference, max_commit_time_ms
):
try:
ret = await coro(self)
except Exception as exc:
if self.in_transaction:
await self.abort_transaction()
if (
isinstance(exc, pymongo.errors.PyMongoError)
and exc.has_error_label("TransientTransactionError")
and _within_time_limit(start_time)
):
# Retry the entire transaction.
continue
raise
if not self.in_transaction:
# Assume callback intentionally ended the transaction.
return ret
while True:
try:
await self.commit_transaction()
except pymongo.errors.PyMongoError as exc:
if (
exc.has_error_label("UnknownTransactionCommitResult")
and _within_time_limit(start_time)
and not _max_time_expired_error(exc)
):
# Retry the commit.
continue
if exc.has_error_label("TransientTransactionError") and _within_time_limit(
start_time
):
# Retry the entire transaction.
break
raise
# Commit succeeded.
return ret
def start_transaction(
self, read_concern=None, write_concern=None, read_preference=None, max_commit_time_ms=None
):
"""Start a multi-statement transaction.
Takes the same arguments as
:class:`~pymongo.client_session.TransactionOptions`.
Best used in a context manager block:
.. code-block:: python3
# Use "await" for start_session, but not for start_transaction.
async with await client.start_session() as s:
async with s.start_transaction():
await collection.delete_one({'x': 1}, session=s)
await collection.insert_one({'x': 2}, session=s)
"""
self.delegate.start_transaction(
read_concern=read_concern,
write_concern=write_concern,
read_preference=read_preference,
max_commit_time_ms=max_commit_time_ms,
)
return _MotorTransactionContext(self)
@property
def client(self):
"""The :class:`~MotorClient` this session was created from."""
return self._client
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
self.delegate.__exit__(exc_type, exc_val, exc_tb)
def __enter__(self):
raise AttributeError(
"Use Motor sessions like 'async with await client.start_session()', not 'with'"
)
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class AgnosticDatabase(AgnosticBaseProperties):
__motor_class_name__ = "MotorDatabase"
__delegate_class__ = Database
__hash__ = DelegateMethod()
__bool__ = DelegateMethod()
command = AsyncCommand(doc=docstrings.cmd_doc)
create_collection = AsyncCommand().wrap(Collection)
dereference = AsyncRead()
drop_collection = AsyncCommand().unwrap("MotorCollection")
get_collection = DelegateMethod().wrap(Collection)
list_collection_names = AsyncRead(doc=docstrings.list_collection_names_doc)
list_collections = AsyncRead()
name = ReadOnlyProperty()
validate_collection = AsyncRead().unwrap("MotorCollection")
with_options = DelegateMethod().wrap(Database)
_async_aggregate = AsyncRead(attr_name="aggregate")
def __init__(self, client, name, **kwargs):
self._client = client
_delegate = kwargs.get("_delegate")
delegate = _delegate if _delegate is not None else Database(client.delegate, name, **kwargs)
super().__init__(delegate)
def aggregate(self, pipeline, *args, **kwargs):
"""Execute an aggregation pipeline on this database.
Introduced in MongoDB 3.6.
The aggregation can be run on a secondary if the client is connected
to a replica set and its ``read_preference`` is not :attr:`PRIMARY`.
The :meth:`aggregate` method obeys the :attr:`read_preference` of this
:class:`MotorDatabase`, except when ``$out`` or ``$merge`` are used, in
which case :attr:`PRIMARY` is used.
All optional `aggregate command`_ parameters should be passed as
keyword arguments to this method. Valid options include, but are not
limited to:
- `allowDiskUse` (bool): Enables writing to temporary files. When set
to True, aggregation stages can write data to the _tmp subdirectory
of the --dbpath directory. The default is False.
- `maxTimeMS` (int): The maximum amount of time to allow the operation
to run in milliseconds.
- `batchSize` (int): The maximum number of documents to return per
batch. Ignored if the connected mongod or mongos does not support
returning aggregate results using a cursor.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`.
- `let` (dict): A dict of parameter names and values. Values must be
constant or closed expressions that do not reference document
fields. Parameters can then be accessed as variables in an
aggregate expression context (e.g. ``"$$var"``). This option is
only supported on MongoDB >= 5.0.
Returns a :class:`MotorCommandCursor` that can be iterated like a
cursor from :meth:`find`::
async def f():
# Lists all operations currently running on the server.
pipeline = [{"$currentOp": {}}]
async for operation in client.admin.aggregate(pipeline):
print(operation)
.. note:: This method does not support the 'explain' option. Please
use :meth:`MotorDatabase.command` instead.
.. note:: The :attr:`MotorDatabase.write_concern` of this database is
automatically applied to this operation.
.. versionadded:: 2.1
.. _aggregate command:
https://www.mongodb.com/docs/manual/reference/command/aggregate/
"""
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__
)
# Latent cursor that will send initial command on first "async for".
return cursor_class(
self["$cmd.aggregate"],
self._async_aggregate,
pipeline,
*unwrap_args_session(args),
**unwrap_kwargs_session(kwargs)
)
def watch(
self,
pipeline=None,
full_document=None,
resume_after=None,
max_await_time_ms=None,
batch_size=None,
collation=None,
start_at_operation_time=None,
session=None,
start_after=None,
comment=None,
):
"""Watch changes on this database.
Returns a :class:`~MotorChangeStream` cursor which iterates over changes
on this database. Introduced in MongoDB 4.0.
See the documentation for :meth:`MotorCollection.watch` for more
details and examples.
:Parameters:
- `pipeline` (optional): 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.
- `full_document` (optional): The fullDocument option to pass
to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
When set to 'updateLookup', the change notification for partial
updates will include both a delta describing the changes to the
document, as well as a copy of the entire document that was
changed from some time after the change occurred.
- `resume_after` (optional): A resume token. If provided, the
change stream will start returning changes that occur directly
after the operation specified in the resume token. A resume token
is the _id value of a change document.
- `max_await_time_ms` (optional): The maximum time in milliseconds
for the server to wait for changes before responding to a getMore
operation.
- `batch_size` (optional): The maximum number of documents to return
per batch.
- `collation` (optional): The :class:`~pymongo.collation.Collation`
to use for the aggregation.
- `start_at_operation_time` (optional): If provided, the resulting
change stream will only return changes that occurred at or after
the specified :class:`~bson.timestamp.Timestamp`. Requires
MongoDB >= 4.0.
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
- `start_after` (optional): The same as `resume_after` except that
`start_after` can resume notifications after an invalidate event.
This option and `resume_after` are mutually exclusive.
- `comment` (optional): A user-provided comment to attach to this
command.
:Returns:
A :class:`~MotorChangeStream`.
.. versionchanged:: 3.0
Added ``comment`` parameter.
.. versionchanged:: 2.1
Added the ``start_after`` parameter.
.. versionadded:: 2.0
.. mongodoc:: changeStreams
"""
cursor_class = create_class_with_framework(
AgnosticChangeStream, self._framework, self.__module__
)
# Latent cursor that will send initial command on first "async for".
return cursor_class(
self,
pipeline,
full_document,
resume_after,
max_await_time_ms,
batch_size,
collation,
start_at_operation_time,
session,
start_after,
comment,
)
@property
def client(self):
"""This MotorDatabase's :class:`MotorClient`."""
return self._client
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(
"%s has no attribute %r. To access the %s"
" collection, use database['%s']." % (self.__class__.__name__, name, name, name)
)
return self[name]
def __getitem__(self, name):
collection_class = create_class_with_framework(
AgnosticCollection, self._framework, self.__module__
)
return collection_class(self, name)
def __call__(self, *args, **kwargs):
database_name = self.delegate.name
client_class_name = self._client.__class__.__name__
if database_name == "open_sync":
raise TypeError(
"%s.open_sync() is unnecessary Motor 0.2, "
"see changelog for details." % client_class_name
)
raise TypeError(
"MotorDatabase object is not callable. If you meant to "
"call the '%s' method on a %s object it is "
"failing because no such method exists." % (database_name, client_class_name)
)
def wrap(self, obj):
if obj.__class__ is Collection:
# Replace pymongo.collection.Collection with MotorCollection.
klass = create_class_with_framework(
AgnosticCollection, self._framework, self.__module__
)
return klass(self, obj.name, _delegate=obj)
elif obj.__class__ is Database:
return self.__class__(self._client, obj.name, _delegate=obj)
else:
return obj
def get_io_loop(self):
return self._client.get_io_loop()
class AgnosticCollection(AgnosticBaseProperties):
__motor_class_name__ = "MotorCollection"
__delegate_class__ = Collection
__hash__ = DelegateMethod()
__bool__ = DelegateMethod()
bulk_write = AsyncCommand(doc=docstrings.bulk_write_doc)
count_documents = AsyncRead()
create_index = AsyncCommand()
create_indexes = AsyncCommand(doc=docstrings.create_indexes_doc)
delete_many = AsyncCommand(doc=docstrings.delete_many_doc)
delete_one = AsyncCommand(doc=docstrings.delete_one_doc)
distinct = AsyncRead()
drop = AsyncCommand(doc=docstrings.drop_doc)
drop_index = AsyncCommand()
drop_indexes = AsyncCommand()
estimated_document_count = AsyncCommand()
find_one = AsyncRead(doc=docstrings.find_one_doc)
find_one_and_delete = AsyncCommand(doc=docstrings.find_one_and_delete_doc)
find_one_and_replace = AsyncCommand(doc=docstrings.find_one_and_replace_doc)
find_one_and_update = AsyncCommand(doc=docstrings.find_one_and_update_doc)
full_name = ReadOnlyProperty()
index_information = AsyncRead(doc=docstrings.index_information_doc)
insert_many = AsyncWrite(doc=docstrings.insert_many_doc)
insert_one = AsyncCommand(doc=docstrings.insert_one_doc)
name = ReadOnlyProperty()
options = AsyncRead()
rename = AsyncCommand()
replace_one = AsyncCommand(doc=docstrings.replace_one_doc)
update_many = AsyncCommand(doc=docstrings.update_many_doc)
update_one = AsyncCommand(doc=docstrings.update_one_doc)
with_options = DelegateMethod().wrap(Collection)
_async_aggregate = AsyncRead(attr_name="aggregate")
_async_aggregate_raw_batches = AsyncRead(attr_name="aggregate_raw_batches")
_async_list_indexes = AsyncRead(attr_name="list_indexes")
def __init__(
self,
database,
name,
codec_options=None,
read_preference=None,
write_concern=None,
read_concern=None,
_delegate=None,
):
db_class = create_class_with_framework(AgnosticDatabase, self._framework, self.__module__)
if not isinstance(database, db_class):
raise TypeError(
"First argument to MotorCollection must be MotorDatabase, not %r" % database
)
delegate = (
_delegate
if _delegate is not None
else Collection(
database.delegate,
name,
codec_options=codec_options,
read_preference=read_preference,
write_concern=write_concern,
read_concern=read_concern,
)
)
super().__init__(delegate)
self.database = database
def __getattr__(self, name):
# Dotted collection name, like "foo.bar".
if name.startswith("_"):
full_name = "%s.%s" % (self.name, name)
raise AttributeError(
"%s has no attribute %r. To access the %s"
" collection, use database['%s']."
% (self.__class__.__name__, name, full_name, full_name)
)
return self[name]
def __getitem__(self, name):
collection_class = create_class_with_framework(
AgnosticCollection, self._framework, self.__module__
)
return collection_class(
self.database, self.name + "." + name, _delegate=self.delegate[name]
)
def __call__(self, *args, **kwargs):
raise TypeError(
"MotorCollection object is not callable. If you meant to "
"call the '%s' method on a MotorCollection object it is "
"failing because no such method exists." % self.delegate.name
)
def find(self, *args, **kwargs):
"""Create a :class:`MotorCursor`. Same parameters as for
PyMongo's :meth:`~pymongo.collection.Collection.find`.
Note that ``find`` does not require an ``await`` expression, because
``find`` merely creates a
:class:`MotorCursor` without performing any operations on the server.
``MotorCursor`` methods such as :meth:`~MotorCursor.to_list`
perform actual operations.
"""
cursor = self.delegate.find(*unwrap_args_session(args), **unwrap_kwargs_session(kwargs))
cursor_class = create_class_with_framework(AgnosticCursor, self._framework, self.__module__)
return cursor_class(cursor, self)
def find_raw_batches(self, *args, **kwargs):
"""Query the database and retrieve batches of raw BSON.
Similar to the :meth:`find` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into another data type, rather than used with PyMongo's
:mod:`bson` module.
.. code-block:: python3
async def get_raw():
cursor = db.test.find_raw_batches()
async for batch in cursor:
print(bson.decode_all(batch))
Note that ``find_raw_batches`` does not support sessions.
.. versionadded:: 2.0
"""
cursor = self.delegate.find_raw_batches(
*unwrap_args_session(args), **unwrap_kwargs_session(kwargs)
)
cursor_class = create_class_with_framework(
AgnosticRawBatchCursor, self._framework, self.__module__
)
return cursor_class(cursor, self)
def aggregate(self, pipeline, *args, **kwargs):
"""Execute an aggregation pipeline on this collection.
The aggregation can be run on a secondary if the client is connected
to a replica set and its ``read_preference`` is not :attr:`PRIMARY`.
:Parameters:
- `pipeline`: a single command or list of aggregation commands
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`, created with
:meth:`~MotorClient.start_session`.
- `**kwargs`: send arbitrary parameters to the aggregate command
All optional `aggregate command`_ parameters should be passed as
keyword arguments to this method. Valid options include, but are not
limited to:
- `allowDiskUse` (bool): Enables writing to temporary files. When set
to True, aggregation stages can write data to the _tmp subdirectory
of the --dbpath directory. The default is False.
- `maxTimeMS` (int): The maximum amount of time to allow the operation
to run in milliseconds.
- `batchSize` (int): The maximum number of documents to return per
batch. Ignored if the connected mongod or mongos does not support
returning aggregate results using a cursor.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collation`.
- `let` (dict): A dict of parameter names and values. Values must be
constant or closed expressions that do not reference document
fields. Parameters can then be accessed as variables in an
aggregate expression context (e.g. ``"$$var"``). This option is
only supported on MongoDB >= 5.0.
Returns a :class:`MotorCommandCursor` that can be iterated like a
cursor from :meth:`find`::
async def f():
pipeline = [{'$project': {'name': {'$toUpper': '$name'}}}]
async for doc in collection.aggregate(pipeline):
print(doc)
Note that this method returns a :class:`MotorCommandCursor` which
lazily runs the aggregate command when first iterated. In order to run
an aggregation with ``$out`` or ``$merge`` the application needs to
iterate the cursor, for example::
cursor = motor_coll.aggregate([{'$out': 'out'}])
# Iterate the cursor to run the $out (or $merge) operation.
await cursor.to_list(length=None)
# Or more succinctly:
await motor_coll.aggregate([{'$out': 'out'}]).to_list(length=None)
# Or:
async for _ in motor_coll.aggregate([{'$out': 'out'}]):
pass
:class:`MotorCommandCursor` does not allow the ``explain`` option. To
explain MongoDB's query plan for the aggregation, use
:meth:`MotorDatabase.command`::
async def f():
plan = await db.command(
'aggregate', 'COLLECTION-NAME',
pipeline=[{'$project': {'x': 1}}],
explain=True)
print(plan)
.. versionchanged:: 2.1
This collection's read concern is now applied to pipelines
containing the `$out` stage when connected to MongoDB >= 4.2.
.. versionchanged:: 1.0
:meth:`aggregate` now **always** returns a cursor.
.. versionchanged:: 0.5
:meth:`aggregate` now returns a cursor by default,
and the cursor is returned immediately without an ``await``.
See :ref:`aggregation changes in Motor 0.5 <aggregate_changes_0_5>`.
.. versionchanged:: 0.2
Added cursor support.
.. _aggregate command:
https://mongodb.com/docs/manual/applications/aggregation
"""
cursor_class = create_class_with_framework(
AgnosticLatentCommandCursor, self._framework, self.__module__
)
# Latent cursor that will send initial command on first "async for".
return cursor_class(
self,
self._async_aggregate,
pipeline,
*unwrap_args_session(args),
**unwrap_kwargs_session(kwargs)
)
def aggregate_raw_batches(self, pipeline, **kwargs):
"""Perform an aggregation and retrieve batches of raw BSON.
Similar to the :meth:`aggregate` method but returns each batch as bytes.
This example demonstrates how to work with raw batches, but in practice
raw batches should be passed to an external library that can decode
BSON into another data type, rather than used with PyMongo's