diff --git a/source/crud.txt b/source/crud.txt index cdf49de2..d8c9e468 100644 --- a/source/crud.txt +++ b/source/crud.txt @@ -53,20 +53,51 @@ the relevant values for your MongoDB deployment. .. include:: /includes/usage-examples/sample-app-intro.rst -.. literalinclude:: /includes/usage-examples/crud-sample-app.py - :language: python - :copyable: true - :linenos: - :emphasize-lines: 4-6 +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the +corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/crud-sample-app.py + :language: python + :copyable: true + :linenos: + :emphasize-lines: 11-13 + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/crud-sample-app-async.py + :language: python + :copyable: true + :linenos: + :emphasize-lines: 13-15 Insert One ---------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-insert-one - :end-before: end-insert-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-insert-one + :end-before: end-insert-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-insert-one + :end-before: end-insert-one + :language: python + :copyable: To learn more about the ``insert_one()`` method, see the :ref:`Insert Documents ` guide. @@ -74,11 +105,26 @@ To learn more about the ``insert_one()`` method, see the :ref:`Insert Documents Insert Multiple --------------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-insert-multiple - :end-before: end-insert-multiple - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-insert-multiple + :end-before: end-insert-multiple + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-insert-multiple + :end-before: end-insert-multiple + :language: python + :copyable: + To learn more about the ``insert_many()`` method, see the :ref:`Insert Documents ` guide. @@ -86,11 +132,25 @@ To learn more about the ``insert_many()`` method, see the :ref:`Insert Documents Update One ---------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-update-one - :end-before: end-update-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-update-one + :end-before: end-update-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-update-one + :end-before: end-update-one + :language: python + :copyable: To learn more about the ``update_one()`` method, see the :ref:`Update Documents ` guide. @@ -98,11 +158,25 @@ To learn more about the ``update_one()`` method, see the Update Multiple --------------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-update-multiple - :end-before: end-update-multiple - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-update-multiple + :end-before: end-update-multiple + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-update-multiple + :end-before: end-update-multiple + :language: python + :copyable: To learn more about the ``update_many()`` method, see the :ref:`Update Documents ` guide. @@ -110,11 +184,25 @@ To learn more about the ``update_many()`` method, see the Replace One ----------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-replace-one - :end-before: end-replace-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-replace-one + :end-before: end-replace-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-replace-one + :end-before: end-replace-one + :language: python + :copyable: To learn more about the ``replace_one()`` method, see the :ref:`Replace Documents ` guide. @@ -122,11 +210,25 @@ To learn more about the ``replace_one()`` method, see the Delete One ---------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-delete-one - :end-before: end-delete-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-delete-one + :end-before: end-delete-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-delete-one + :end-before: end-delete-one + :language: python + :copyable: To learn more about the ``delete_one()`` method, see the :ref:`Delete Documents ` guide. @@ -134,11 +236,25 @@ To learn more about the ``delete_one()`` method, see the Delete Multiple --------------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-delete-multiple - :end-before: end-delete-multiple - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-delete-multiple + :end-before: end-delete-multiple + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-delete-multiple + :end-before: end-delete-multiple + :language: python + :copyable: To learn more about the ``delete_many()`` method, see the :ref:`Delete Documents ` guide. @@ -146,11 +262,25 @@ To learn more about the ``delete_many()`` method, see the Bulk Write ---------- -.. literalinclude:: /includes/usage-examples/write-code-examples.py - :start-after: start-bulk-write - :end-before: end-bulk-write - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/write-code-examples.py + :start-after: start-bulk-write + :end-before: end-bulk-write + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/write-code-examples-async.py + :start-after: start-bulk-write + :end-before: end-bulk-write + :language: python + :copyable: To learn more about the ``bulk_write()`` method, see the :ref:`Bulk Write ` guide. @@ -158,11 +288,25 @@ To learn more about the ``bulk_write()`` method, see the Find One -------- -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-find-one - :end-before: end-find-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-find-one + :end-before: end-find-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-find-one + :end-before: end-find-one + :language: python + :copyable: To learn more about the ``find_one()`` method, see :ref:`pymongo-retrieve-find-one` in the Retrieve Data guide. @@ -170,11 +314,25 @@ the Retrieve Data guide. Find Multiple ------------- -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-find - :end-before: end-find - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-find + :end-before: end-find + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-find + :end-before: end-find + :language: python + :copyable: To learn more about the ``find()`` method, see :ref:`pymongo-retrieve-find-multiple` in the Retrieve Data guide. @@ -182,11 +340,25 @@ the Retrieve Data guide. Count Documents in a Collection ------------------------------- -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-count-all - :end-before: end-count-all - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-count-all + :end-before: end-count-all + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-count-all + :end-before: end-count-all + :language: python + :copyable: To learn more about the ``count_documents()`` method, see the :ref:`pymongo-accurate-count` guide. @@ -194,11 +366,25 @@ To learn more about the ``count_documents()`` method, see the Count Documents Returned from a Query ------------------------------------- -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-count-query - :end-before: end-count-query - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-count-query + :end-before: end-count-query + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-count-query + :end-before: end-count-query + :language: python + :copyable: To learn more about the ``count_documents()`` method, see the :ref:`pymongo-accurate-count` guide. @@ -206,11 +392,25 @@ To learn more about the ``count_documents()`` method, see the Estimated Document Count ------------------------ -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-estimated-count - :end-before: end-estimated-count - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-estimated-count + :end-before: end-estimated-count + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-estimated-count + :end-before: end-estimated-count + :language: python + :copyable: To learn more about the ``estimated_document_count()`` method, see the :ref:`pymongo-estimated-count` guide. @@ -218,11 +418,25 @@ To learn more about the ``estimated_document_count()`` method, see the Retrieve Distinct Values ------------------------ -.. literalinclude:: /includes/usage-examples/retrieve-code-examples.py - :start-after: start-distinct - :end-before: end-distinct - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples.py + :start-after: start-distinct + :end-before: end-distinct + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/usage-examples/retrieve-code-examples-async.py + :start-after: start-distinct + :end-before: end-distinct + :language: python + :copyable: To learn more about the ``distinct()`` method, see the :ref:`pymongo-distinct` guide. diff --git a/source/crud/bulk-write.txt b/source/crud/bulk-write.txt index aba977fa..cacf5b15 100644 --- a/source/crud/bulk-write.txt +++ b/source/crud/bulk-write.txt @@ -266,22 +266,46 @@ Collection Bulk Write Example The following example performs multiple write operations on the ``restaurants`` collection by using the ``bulk_write()`` method -on a ``Collection`` instance: +on a ``Collection`` instance. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: -.. io-code-block:: - :copyable: +.. tabs:: - .. input:: /includes/write/bulk-write.py - :start-after: start-bulk-write-mixed-collection - :end-before: end-bulk-write-mixed-collection - :language: python + .. tab:: Synchronous + :tabid: sync - .. output:: - :visible: false - - BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, - 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, - acknowledged=True) + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write.py + :start-after: start-bulk-write-mixed-collection + :end-before: end-bulk-write-mixed-collection + :language: python + + .. output:: + :visible: false + + BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, + 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, + acknowledged=True) + + .. tab:: Asynchronous + :tabid: async + + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write-async.py + :start-after: start-bulk-write-mixed-collection + :end-before: end-bulk-write-mixed-collection + :language: python + + .. output:: + :visible: false + + BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, + 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, + acknowledged=True) .. _pymongo-bulk-write-client-ex: @@ -291,23 +315,48 @@ Client Bulk Write Example The following example performs multiple write operations on the ``sample_restaurants.restaurants`` and ``sample_mflix.movies`` namespaces by using the ``bulk_write()`` method on a ``MongoClient`` -instance: - -.. io-code-block:: - :copyable: - - .. input:: /includes/write/bulk-write.py - :start-after: start-bulk-write-mixed-client - :end-before: end-bulk-write-mixed-client - :language: python - - .. output:: - :visible: false - - ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], - 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, - 'nModified': 1, 'nDeleted': 344, 'insertResults': {}, 'updateResults': {}, - 'deleteResults': {}}, acknowledged=True, verbose=False) +instance. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the +corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write.py + :start-after: start-bulk-write-mixed-client + :end-before: end-bulk-write-mixed-client + :language: python + + .. output:: + :visible: false + + ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], + 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, + 'nModified': 1, 'nDeleted': 344, 'insertResults': {}, 'updateResults': {}, + 'deleteResults': {}}, acknowledged=True, verbose=False) + + .. tab:: Asynchronous + :tabid: async + + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write-async.py + :start-after: start-bulk-write-mixed-client + :end-before: end-bulk-write-mixed-client + :language: python + + .. output:: + :visible: false + + ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], + 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, + 'nModified': 1, 'nDeleted': 344, 'insertResults': {}, 'updateResults': {}, + 'deleteResults': {}}, acknowledged=True, verbose=False) Customize Bulk Write Operations ------------------------------- @@ -363,14 +412,29 @@ to the ``Collection.bulk_write()`` method: The following example calls the ``bulk_write()`` method from the preceding :ref:`pymongo-bulk-write-collection-ex` but sets the ``ordered`` option -to ``False``: +to ``False``. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see +the corresponding code: -.. literalinclude:: /includes/write/bulk-write.py - :start-after: start-bulk-write-unordered - :end-before: end-bulk-write-unordered - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/bulk-write.py + :start-after: start-bulk-write-unordered + :end-before: end-bulk-write-unordered + :language: python + :copyable: + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/bulk-write-async.py + :start-after: start-bulk-write-unordered + :end-before: end-bulk-write-unordered + :language: python + :copyable: + If any of the write operations in an unordered bulk write fail, {+driver-short+} reports the errors only after attempting all operations. @@ -436,25 +500,53 @@ to the ``MongoClient.bulk_write()`` method: The following example calls the ``bulk_write()`` method from the preceding :ref:`pymongo-bulk-write-client-ex` but sets the ``verbose_results`` option -to ``True``: - -.. io-code-block:: - :copyable: +to ``True``. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see +the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write.py + :start-after: start-bulk-write-verbose + :end-before: end-bulk-write-verbose + :language: python + + .. output:: + :visible: false + + ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], + 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, 'nModified': 1, + 'nDeleted': 344, 'insertResults': {0: InsertOneResult(ObjectId('...'), + acknowledged=True)}, 'updateResults': {1: UpdateResult({'ok': 1.0, 'idx': 1, 'n': 1, + 'nModified': 1}, acknowledged=True)}, 'deleteResults': {2: DeleteResult({'ok': 1.0, + 'idx': 2, 'n': 344}, acknowledged=True)}}, acknowledged=True, verbose=True) + + .. tab:: Asynchronous + :tabid: async + + .. io-code-block:: + :copyable: + + .. input:: /includes/write/bulk-write-async.py + :start-after: start-bulk-write-verbose + :end-before: end-bulk-write-verbose + :language: python + + .. output:: + :visible: false + + ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], + 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, 'nModified': 1, + 'nDeleted': 344, 'insertResults': {0: InsertOneResult(ObjectId('...'), + acknowledged=True)}, 'updateResults': {1: UpdateResult({'ok': 1.0, 'idx': 1, 'n': 1, + 'nModified': 1}, acknowledged=True)}, 'deleteResults': {2: DeleteResult({'ok': 1.0, + 'idx': 2, 'n': 344}, acknowledged=True)}}, acknowledged=True, verbose=True) - .. input:: /includes/write/bulk-write.py - :start-after: start-bulk-write-verbose - :end-before: end-bulk-write-verbose - :language: python - - .. output:: - :visible: false - - ClientBulkWriteResult({'anySuccessful': True, 'error': None, 'writeErrors': [], - 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 1, 'nModified': 1, - 'nDeleted': 344, 'insertResults': {0: InsertOneResult(ObjectId('...'), - acknowledged=True)}, 'updateResults': {1: UpdateResult({'ok': 1.0, 'idx': 1, 'n': 1, - 'nModified': 1}, acknowledged=True)}, 'deleteResults': {2: DeleteResult({'ok': 1.0, - 'idx': 2, 'n': 344}, acknowledged=True)}}, acknowledged=True, verbose=True) Return Values ------------- diff --git a/source/crud/delete.txt b/source/crud/delete.txt index d94d0000..a70b080a 100644 --- a/source/crud/delete.txt +++ b/source/crud/delete.txt @@ -64,25 +64,55 @@ Delete One Document ~~~~~~~~~~~~~~~~~~~ The following example uses the ``delete_one()`` method to remove a document in -the ``restaurants`` collection with a ``name`` value of ``"Ready Penny Inn"``: +the ``restaurants`` collection with a ``name`` value of ``"Ready Penny Inn"``. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: -.. literalinclude:: /includes/write/delete.py - :start-after: start-delete-one - :end-before: end-delete-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/delete.py + :start-after: start-delete-one + :end-before: end-delete-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/delete-async.py + :start-after: start-delete-one + :end-before: end-delete-one + :language: python + :copyable: Delete Multiple Documents ~~~~~~~~~~~~~~~~~~~~~~~~~ The following example uses the ``delete_many()`` method to remove all documents -in the ``restaurants`` collection with a ``borough`` value of ``"Brooklyn"``: +in the ``restaurants`` collection with a ``borough`` value of ``"Brooklyn"``. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/delete.py + :start-after: start-delete-many + :end-before: end-delete-many + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/write/delete.py - :start-after: start-delete-many - :end-before: end-delete-many - :language: python - :copyable: + .. literalinclude:: /includes/write/delete-async.py + :start-after: start-delete-many + :end-before: end-delete-many + :language: python + :copyable: Customize the Delete Operation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -125,13 +155,28 @@ the delete operation. The following code uses the ``delete_many()`` method to delete all documents in the ``restaurants`` collection with a ``name`` value that includes the string ``"Mongo"``. -It also uses the ``comment`` option to add a comment to the operation: +It also uses the ``comment`` option to add a comment to the operation. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: -.. literalinclude:: /includes/write/delete.py - :start-after: start-delete-options - :end-before: end-delete-options - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/delete.py + :start-after: start-delete-options + :end-before: end-delete-options + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/delete-async.py + :start-after: start-delete-options + :end-before: end-delete-options + :language: python + :copyable: .. tip:: @@ -150,13 +195,28 @@ use. .. include:: /includes/collation-description.rst The following example performs the same delete operation as the previous example, -but with a default collation of ``fr_CA``: +but with a default collation of ``fr_CA``. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/delete.py + :start-after: start-delete-many-collation + :end-before: end-delete-many-collation + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/write/delete.py - :start-after: start-delete-many-collation - :end-before: end-delete-many-collation - :language: python - :copyable: + .. literalinclude:: /includes/write/delete-async.py + :start-after: start-delete-many-collation + :end-before: end-delete-many-collation + :language: python + :copyable: .. include:: /includes/collation-override-note.rst diff --git a/source/crud/geo.txt b/source/crud/geo.txt index 3e7e759f..c6b84417 100644 --- a/source/crud/geo.txt +++ b/source/crud/geo.txt @@ -200,97 +200,199 @@ Query by Proximity The following example queries for documents with a ``location.geo`` field value within 1000 meters of the MongoDB Headquarters in New York City, NY. It returns documents -from nearest to farthest. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: python - - # set query with point at MongoDB headquarters and a maxDistance of 1000 meters - query = { - "location.geo": { - "$near": { - "$geometry": { - # Search around this location - "type": "Point", - "coordinates": [-73.986805, 40.7620853] - }, - "$maxDistance": 1000 # Distance in meters (1 km) - } - } - } +from nearest to farthest. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: - # fetches the _id and theaterId fields - projection = { "theaterId": 1 } +.. tabs:: - nearby_places = location.find(query, projection) + .. tab:: Synchronous + :tabid: sync - for i in nearby_places: - print(i) + .. io-code-block:: + :copyable: true - .. output:: - :language: json - :visible: false + .. input:: + :language: python - { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } - { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } + # set query with point at MongoDB headquarters and a maxDistance of 1000 meters + query = { + "location.geo": { + "$near": { + "$geometry": { + # Search around this location + "type": "Point", + "coordinates": [-73.986805, 40.7620853] + }, + "$maxDistance": 1000 # Distance in meters (1 km) + } + } + } -Query by Polygon -~~~~~~~~~~~~~~~~ + # fetches the _id and theaterId fields + projection = { "theaterId": 1 } -The following example queries for documents with a ``location.geo`` field value that exists -within the boundaries of Manhattan. - -.. io-code-block:: - :copyable: true - - .. input:: - :language: python - - # Polygon representation of Manhattan - query = { - "location.geo": { - "$geoWithin": { - "$geometry": { - # Search around this location - "type": "Polygon", - "coordinates": - [[[-73.925492, 40.877410], - [-73.910372, 40.872366], - [-73.935127, 40.834020], - [-73.929049, 40.798569], - [-73.976485, 40.711432], - [-74.015747, 40.701229], - [-74.018859, 40.708367], - [-74.008007, 40.754307], - [-73.925492, 40.877410]]] - } - } - } - } + nearby_places = collection.find(query, projection) + + for i in nearby_places: + print(i) + + .. output:: + :language: json + :visible: false + + { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } + + .. tab:: Asynchronous + :tabid: async + + .. io-code-block:: + :copyable: true - # fetches the _id and theaterId fields - projection = { "theaterId": 1 } + .. input:: + :language: python - nearby_places = location.find(query, projection) + # set query with point at MongoDB headquarters and a maxDistance of 1000 meters + query = { + "location.geo": { + "$near": { + "$geometry": { + # Search around this location + "type": "Point", + "coordinates": [-73.986805, 40.7620853] + }, + "$maxDistance": 1000 # Distance in meters (1 km) + } + } + } - for i in nearby_places: - print(i) + # fetches the _id and theaterId fields + projection = { "theaterId": 1 } - .. output:: - :language: json - :visible: false + nearby_places = collection.find(query, projection) - { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } - { "_id" : ObjectId("59a47287cfa9a3a73e51eccb"), "theaterId" : 835 } - { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } - { "_id" : ObjectId("59a47286cfa9a3a73e51e744"), "theaterId" : 1028 } - { "_id" : ObjectId("59a47287cfa9a3a73e51ebe1"), "theaterId" : 609 } - { "_id" : ObjectId("59a47287cfa9a3a73e51e8ed"), "theaterId" : 1906 } - { "_id" : ObjectId("59a47287cfa9a3a73e51e87d"), "theaterId" : 1531 } - { "_id" : ObjectId("59a47287cfa9a3a73e51eb63"), "theaterId" : 482 } + async for i in nearby_places: + print(i) + + .. output:: + :language: json + :visible: false + + { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } + +Query by Polygon +~~~~~~~~~~~~~~~~ + +The following example queries for documents with a ``location.geo`` field value that exists +within the boundaries of Manhattan. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. io-code-block:: + :copyable: true + + .. input:: + :language: python + + # Polygon representation of Manhattan + query = { + "location.geo": { + "$geoWithin": { + "$geometry": { + # Search around this location + "type": "Polygon", + "coordinates": + [[[-73.925492, 40.877410], + [-73.910372, 40.872366], + [-73.935127, 40.834020], + [-73.929049, 40.798569], + [-73.976485, 40.711432], + [-74.015747, 40.701229], + [-74.018859, 40.708367], + [-74.008007, 40.754307], + [-73.925492, 40.877410]]] + } + } + } + } + + # fetches the _id and theaterId fields + projection = { "theaterId": 1 } + + nearby_places = collection.find(query, projection) + + for i in nearby_places: + print(i) + + .. output:: + :language: json + :visible: false + + { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } + { "_id" : ObjectId("59a47287cfa9a3a73e51eccb"), "theaterId" : 835 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e744"), "theaterId" : 1028 } + { "_id" : ObjectId("59a47287cfa9a3a73e51ebe1"), "theaterId" : 609 } + { "_id" : ObjectId("59a47287cfa9a3a73e51e8ed"), "theaterId" : 1906 } + { "_id" : ObjectId("59a47287cfa9a3a73e51e87d"), "theaterId" : 1531 } + { "_id" : ObjectId("59a47287cfa9a3a73e51eb63"), "theaterId" : 482 } + + .. tab:: Asynchronous + :tabid: async + + .. io-code-block:: + :copyable: true + + .. input:: + :language: python + + # Polygon representation of Manhattan + query = { + "location.geo": { + "$geoWithin": { + "$geometry": { + # Search around this location + "type": "Polygon", + "coordinates": + [[[-73.925492, 40.877410], + [-73.910372, 40.872366], + [-73.935127, 40.834020], + [-73.929049, 40.798569], + [-73.976485, 40.711432], + [-74.015747, 40.701229], + [-74.018859, 40.708367], + [-74.008007, 40.754307], + [-73.925492, 40.877410]]] + } + } + } + } + + # fetches the _id and theaterId fields + projection = { "theaterId": 1 } + + nearby_places = collection.find(query, projection) + + async for i in nearby_places: + print(i) + + .. output:: + :language: json + :visible: false + + { "_id" : ObjectId("59a47287cfa9a3a73e51e8e2"), "theaterId" : 1908 } + { "_id" : ObjectId("59a47287cfa9a3a73e51eccb"), "theaterId" : 835 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e838"), "theaterId" : 1448 } + { "_id" : ObjectId("59a47286cfa9a3a73e51e744"), "theaterId" : 1028 } + { "_id" : ObjectId("59a47287cfa9a3a73e51ebe1"), "theaterId" : 609 } + { "_id" : ObjectId("59a47287cfa9a3a73e51e8ed"), "theaterId" : 1906 } + { "_id" : ObjectId("59a47287cfa9a3a73e51e87d"), "theaterId" : 1531 } + { "_id" : ObjectId("59a47287cfa9a3a73e51eb63"), "theaterId" : 482 } Additional Resources -------------------- diff --git a/source/crud/gridfs.txt b/source/crud/gridfs.txt index 7fbd67ff..415ab88f 100644 --- a/source/crud/gridfs.txt +++ b/source/crud/gridfs.txt @@ -79,25 +79,58 @@ Create a GridFS Bucket To store or retrieve files from GridFS, create a GridFS bucket by calling the ``GridFSBucket()`` constructor and passing in a ``Database`` instance. You can use the ``GridFSBucket`` instance to -call read and write operations on the files in your bucket. +call read and write operations on the files in your bucket. If you are working with an +asynchronous application, use the ``AsyncGridFSBucket()`` constructor instead. -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start create bucket - :end-before: end create bucket +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start create bucket + :end-before: end create bucket + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start create bucket + :end-before: end create bucket .. _gridfs-create-custom-bucket: To create or reference a bucket with a custom name other than the default name ``fs``, pass your bucket name as the second parameter to the ``GridFSBucket()`` -constructor, as shown below: +constructor, as shown in the following example. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start create custom bucket + :end-before: end create custom bucket + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start create custom bucket - :end-before: end create custom bucket + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start create custom bucket + :end-before: end create custom bucket .. _gridfs-upload-files: @@ -109,13 +142,28 @@ create an upload stream for a given file name. The ``open_upload_stream()`` method allows you to specify configuration information such as file chunk size and other field/value pairs to store as metadata. Set these options as parameters of ``open_upload_stream()``, as shown in the following code -example: +example. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the +corresponding code: -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start upload files - :end-before: end upload files +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start upload files + :end-before: end upload files + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start upload files + :end-before: end upload files .. _gridfs-retrieve-file-info: @@ -139,13 +187,28 @@ from which you can access the results. To learn more about ``Cursor`` objects in The following code example shows you how to retrieve and print file metadata from all your files in a GridFS bucket. It uses the ``for...in`` syntax to traverse the -``Cursor`` iterable and display the results: +``Cursor`` iterable and display the results. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start retrieve file info + :end-before: end retrieve file info + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start retrieve file info - :end-before: end retrieve file info + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start retrieve file info + :end-before: end retrieve file info The ``find()`` method accepts various query specifications. You can use its parameters to specify the sort order, maximum number of documents to return, @@ -162,13 +225,28 @@ You can download files from your MongoDB database by using the download stream. The following example shows you how to download a file referenced -by the file name, ``"my_file"``, and read its contents: +by the file name, ``"my_file"``, and read its contents. Select the :guilabel:`Synchronous` +or :guilabel:`Asynchronous` tab to see the corresponding code: -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start download files name - :end-before: end download files name +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start download files name + :end-before: end download files name + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start download files name + :end-before: end download files name .. note:: @@ -177,13 +255,28 @@ by the file name, ``"my_file"``, and read its contents: determined by the ``uploadDate`` field). Alternatively, you can use the ``open_download_stream()`` -method, which takes the ``_id`` field of a file as a parameter: +method, which takes the ``_id`` field of a file as a parameter. Select the :guilabel:`Synchronous` +or :guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start download files id + :end-before: end download files id + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start download files id - :end-before: end download files id + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start download files id + :end-before: end download files id .. note:: @@ -203,13 +296,28 @@ bucket. You must specify the file to rename by its ``_id`` field rather than its file name. The following example shows how to update the ``filename`` field to -``"new_file_name"`` by referencing a document's ``_id`` field: +``"new_file_name"`` by referencing a document's ``_id`` field. Select the :guilabel:`Synchronous` +or :guilabel:`Asynchronous` tab to see the corresponding code: -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start rename files - :end-before: end rename files +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start rename files + :end-before: end rename files + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start rename files + :end-before: end rename files .. note:: @@ -228,13 +336,29 @@ Use the ``delete()`` method to remove a file's collection document and associate chunks from your bucket. This effectively deletes the file. You must specify the file by its ``_id`` field rather than its file name. -The following example shows you how to delete a file by referencing its ``_id`` field: +The following example shows you how to delete a file by referencing its ``_id`` field. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the +corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/gridfs/gridfs.py + :language: python + :dedent: + :start-after: start delete files + :end-before: end delete files + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/gridfs/gridfs.py - :language: python - :dedent: - :start-after: start delete files - :end-before: end delete files + .. literalinclude:: /includes/gridfs/gridfs-async.py + :language: python + :dedent: + :start-after: start delete files + :end-before: end delete files .. note:: diff --git a/source/crud/insert.txt b/source/crud/insert.txt index 2ff21666..ee9ce431 100644 --- a/source/crud/insert.txt +++ b/source/crud/insert.txt @@ -54,12 +54,26 @@ Insert One Document To add a single document to a MongoDB collection, call the ``insert_one()`` method and pass the document you want to add. -The following example inserts a document into the ``restaurants`` collection: +The following example inserts a document into the ``restaurants`` collection. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: -.. code-block:: python - :copyable: true +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + :copyable: true + + sample_restaurants.restaurants.insert_one({"name" : "Mongo's Burgers"}) + + .. tab:: Asynchronous + :tabid: async + + .. code-block:: python + :copyable: true - sample_restaurants.restaurants.insert_one({"name" : "Mongo's Burgers"}) + await sample_restaurants.restaurants.insert_one({"name" : "Mongo's Burgers"}) You can also pass an instance of a custom class to the ``insert_one()`` method. This provides additional type safety if you're using a type-checking @@ -70,15 +84,32 @@ tool. The instance you pass must inherit from the ``TypedDict`` class. .. include:: /includes/type-hints/typeddict-availability.rst The following example passes an instance of the ``Restaurant`` class to the ``insert_one()`` -method for added type safety: +method for added type safety. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: -.. code-block:: python - :copyable: true +.. tabs:: - class Restaurant(TypedDict): - name: str - - sample_restaurants.restaurants.insert_one(Restaurant(name="Mongo's Burgers") + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + :copyable: true + + class Restaurant(TypedDict): + name: str + + sample_restaurants.restaurants.insert_one(Restaurant(name="Mongo's Burgers")) + + .. tab:: Asynchronous + :tabid: async + + .. code-block:: python + :copyable: true + + class Restaurant(TypedDict): + name: str + + await sample_restaurants.restaurants.insert_one(Restaurant(name="Mongo's Burgers")) .. include:: /includes/type-hints/tip-type-checkers.rst @@ -88,17 +119,37 @@ Insert Multiple Documents To add multiple documents to a MongoDB collection, call the ``insert_many()`` method and pass a list of documents you want to add. -The following example inserts a list of documents into the ``restaurants`` collection: +The following example inserts a list of documents into the ``restaurants`` collection. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code: -.. code-block:: python - :copyable: true +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + :copyable: true + + document_list = [ + { "name" : "Mongo's Burgers" }, + { "name" : "Mongo's Pizza" } + ] + + sample_restaurants.restaurants.insert_many(document_list) - document_list = [ - { "name" : "Mongo's Burgers" }, - { "name" : "Mongo's Pizza" } - ] + .. tab:: Asynchronous + :tabid: async - sample_restaurants.restaurants.insert_many(document_list) + .. code-block:: python + :copyable: true + + document_list = [ + { "name" : "Mongo's Burgers" }, + { "name" : "Mongo's Pizza" } + ] + + await sample_restaurants.restaurants.insert_many(document_list) You can also pass a list of instances of a custom class to the ``insert_many()`` method. This provides additional type safety if you're using a type-checking @@ -110,19 +161,42 @@ tool. The instances you pass must inherit from the ``TypedDict`` class. The following example calls the ``insert_many()`` method and passes a list that contains instances of the ``Restaurant`` class. This adds type safety to the insert operation. +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code: -.. code-block:: python - :copyable: true +.. tabs:: - class Restaurant(TypedDict): - name: str - - document_list = [ - Restaurant(name="Mongo's Burgers"), - Restaurant(name="Mongo's Pizza") - ] + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + :copyable: true + + class Restaurant(TypedDict): + name: str + + document_list = [ + Restaurant(name="Mongo's Burgers"), + Restaurant(name="Mongo's Pizza") + ] + + sample_restaurants.restaurants.insert_many(document_list) + + .. tab:: Asynchronous + :tabid: async - sample_restaurants.restaurants.insert_many(document_list) + .. code-block:: python + :copyable: true + + class Restaurant(TypedDict): + name: str + + document_list = [ + Restaurant(name="Mongo's Burgers"), + Restaurant(name="Mongo's Pizza") + ] + + await sample_restaurants.restaurants.insert_many(document_list) .. include:: /includes/type-hints/tip-type-checkers.rst @@ -176,17 +250,38 @@ Example The following code uses the ``insert_many()`` method to insert three new documents into a collection. Because the second method argument is ``bypass_document_validation = True``, this insert operation bypasses -document-level validation. +document-level validation. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: -.. code-block:: python +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. code-block:: python + :copyable: true + + document_list = [ + { "name" : "Mongo's Burgers" }, + { "name" : "Mongo's Pizza" }, + { "name" : "Mongo's Tacos" } + ] + + sample_restaurants.restaurants.insert_many(document_list, bypass_document_validation = True) + + .. tab:: Asynchronous + :tabid: async + + .. code-block:: python + :copyable: true - document_list = [ - { "name" : "Mongo's Burgers" }, - { "name" : "Mongo's Pizza" }, - { "name" : "Mongo's Tacos" } - ] + document_list = [ + { "name" : "Mongo's Burgers" }, + { "name" : "Mongo's Pizza" }, + { "name" : "Mongo's Tacos" } + ] - sample_restaurants.restaurants.insert_many(document_list, bypass_document_validation = True) + await sample_restaurants.restaurants.insert_many(document_list, bypass_document_validation = True) Troubleshooting --------------- diff --git a/source/crud/transactions.txt b/source/crud/transactions.txt index e069e189..c80e5077 100644 --- a/source/crud/transactions.txt +++ b/source/crud/transactions.txt @@ -186,12 +186,30 @@ following steps: ensures that the session closes properly when the block exits. #. Close the connection to the server by using the ``client.close()`` method. -.. literalinclude:: /includes/write/transaction.py - :start-after: start-transaction - :end-before: end-transaction - :language: python - :copyable: - :dedent: +Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding +code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/transaction.py + :start-after: start-transaction + :end-before: end-transaction + :language: python + :copyable: + :dedent: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/transaction-async.py + :start-after: start-transaction + :end-before: end-transaction + :language: python + :copyable: + :dedent: If you require more control over your transactions, you can use the ``start_transaction()`` method. You can use this method with the ``commit_transaction()`` and ``abort_transaction()`` diff --git a/source/crud/update.txt b/source/crud/update.txt index a1968a2d..49a37c25 100644 --- a/source/crud/update.txt +++ b/source/crud/update.txt @@ -67,26 +67,56 @@ Update One Document ~~~~~~~~~~~~~~~~~~~ The following example uses the ``update_one()`` method to update the ``name`` value of a -document named ``"Bagels N Buns"`` in the ``restaurants`` collection: +document named ``"Bagels N Buns"`` in the ``restaurants`` collection. Select the +:guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding code: -.. literalinclude:: /includes/write/update.py - :start-after: start-update-one - :end-before: end-update-one - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/update.py + :start-after: start-update-one + :end-before: end-update-one + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/update-async.py + :start-after: start-update-one + :end-before: end-update-one + :language: python + :copyable: Update Many Documents ~~~~~~~~~~~~~~~~~~~~~ The following example uses the ``update_many()`` method to update all documents with a ``cuisine`` value of ``"Pizza"``. After the update, the documents have a -``cuisine`` value of ``"Pasta"``. +``cuisine`` value of ``"Pasta"``. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/update.py + :start-after: start-update-many + :end-before: end-update-many + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/write/update.py - :start-after: start-update-many - :end-before: end-update-many - :language: python - :copyable: + .. literalinclude:: /includes/write/update-async.py + :start-after: start-update-many + :end-before: end-update-many + :language: python + :copyable: Customize the Update Operation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -150,13 +180,28 @@ The following code uses the ``update_many()`` method to find all documents where ``borough`` field has the value ``"Manhattan"``. It then updates the ``borough`` value in these documents to ``"Manhattan (north)"``. Because the ``upsert`` option is set to ``True``, {+driver-short+} inserts a new document if the query filter doesn't -match any existing documents. +match any existing documents. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` +tab to see the corresponding code: -.. literalinclude:: /includes/write/update.py - :start-after: start-update-options - :end-before: end-update-options - :language: python - :copyable: +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/update.py + :start-after: start-update-options + :end-before: end-update-options + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async + + .. literalinclude:: /includes/write/update-async.py + :start-after: start-update-options + :end-before: end-update-options + :language: python + :copyable: .. _pymongo-update-collation: @@ -169,13 +214,28 @@ use. .. include:: /includes/collation-description.rst The following example performs the same update operation as the previous example, -but with a default collation of ``fr_CA``: +but with a default collation of ``fr_CA``. Select the :guilabel:`Synchronous` or +:guilabel:`Asynchronous` tab to see the corresponding code: + +.. tabs:: + + .. tab:: Synchronous + :tabid: sync + + .. literalinclude:: /includes/write/update.py + :start-after: start-update-many-collation + :end-before: end-update-many-collation + :language: python + :copyable: + + .. tab:: Asynchronous + :tabid: async -.. literalinclude:: /includes/write/update.py - :start-after: start-update-many-collation - :end-before: end-update-many-collation - :language: python - :copyable: + .. literalinclude:: /includes/write/update-async.py + :start-after: start-update-many-collation + :end-before: end-update-many-collation + :language: python + :copyable: .. include:: /includes/collation-override-note.rst diff --git a/source/includes/gridfs/gridfs-async.py b/source/includes/gridfs/gridfs-async.py new file mode 100644 index 00000000..1a185b08 --- /dev/null +++ b/source/includes/gridfs/gridfs-async.py @@ -0,0 +1,39 @@ +# start create bucket +client = AsyncMongoClient("") +db = client["db"] +bucket = gridfs.AsyncGridFSBucket(db) +# end create bucket + +# start create custom bucket +custom_bucket = gridfs.AsyncGridFSBucket(db, bucket_name="myCustomBucket") +# end create custom bucket + +# start upload files +async with bucket.open_upload_stream( + "my_file", chunk_size_bytes=1048576, metadata={"contentType": "text/plain"} +) as grid_in: + await grid_in.write("data to store") +# end upload files + +# start retrieve file info +async for file_doc in bucket.find({}): + print(file_doc) +# end retrieve file info + +# start download files name +file = await bucket.open_download_stream_by_name("my_file") +contents = await file.read() +# end download files name + +# start download files id +file = await bucket.open_download_stream(ObjectId("66b3c86e672a17b6c8a4a4a9")) +contents = await file.read() +# end download files id + +# start rename files +await bucket.rename(ObjectId("66b3c86e672a17b6c8a4a4a9"), "new_file_name") +# end rename files + +# start delete files +await bucket.delete(ObjectId("66b3c86e672a17b6c8a4a4a9")) +# end delete files diff --git a/source/includes/usage-examples/write-code-examples-async.py b/source/includes/usage-examples/write-code-examples-async.py new file mode 100644 index 00000000..a38d959a --- /dev/null +++ b/source/includes/usage-examples/write-code-examples-async.py @@ -0,0 +1,82 @@ +# start-insert-one +result = await collection.insert_one({ "" : "" }) + +print(result.acknowledged) +# end-insert-one + +# start-insert-multiple +document_list = [ + { "" : "" }, + { "" : "" } +] + +result = await collection.insert_many(document_list) + +print(result.acknowledged) +# end-insert-multiple + +# start-update-one +query_filter = { "" : "" } +update_operation = { "$set" : + { "" : "" } +} +result = await collection.update_one(query_filter, update_operation) + +print(result.modified_count) +# end-update-one + +# start-update-multiple +query_filter = { "" : "" } +update_operation = { "$set" : + { "" : "" } +} +result = await collection.update_many(query_filter, update_operation) + +print(result.modified_count) +# end-update-multiple + +# start-replace-one +query_filter = { "" : "" } +replace_document = { "" : "" } + +result = await collection.replace_one(query_filter, replace_document) + +print(result.modified_count) +# end-replace-one + +# start-delete-one +query_filter = { "" : "" } + +result = await collection.delete_one(query_filter) + +print(result.deleted_count) +# end-delete-one + +# start-delete-multiple +query_filter = { "" : "" } + +result = await collection.delete_many(query_filter) + +print(result.deleted_count) +# end-delete-multiple + +# start-bulk-write +operations = [ + pymongo.InsertOne( + { + "" : "" + } + ), + pymongo.UpdateMany( + { "" : "" }, + { "$set" : { "" : "" }}, + ), + pymongo.DeleteOne( + { "" : "" } + ), +] + +result = await collection.bulk_write(operations) + +print(result) +# end-bulk-write \ No newline at end of file diff --git a/source/includes/write/bulk-write-async.py b/source/includes/write/bulk-write-async.py new file mode 100644 index 00000000..462e4694 --- /dev/null +++ b/source/includes/write/bulk-write-async.py @@ -0,0 +1,66 @@ +# start-bulk-write-mixed-collection +operations = [ + InsertOne( + document={ + "name": "Mongo's Deli", + "cuisine": "Sandwiches", + "borough": "Manhattan", + "restaurant_id": "1234" + } + ), + InsertOne( + document={ + "name": "Mongo's Deli", + "cuisine": "Sandwiches", + "borough": "Brooklyn", + "restaurant_id": "5678" + } + ), + UpdateMany( + filter={ "name": "Mongo's Deli" }, + update={ "$set": { "cuisine": "Sandwiches and Salads" }} + ), + DeleteOne( + filter={ "restaurant_id": "1234" } + ) +] + +results = await restaurants.bulk_write(operations) + +print(results) +# end-bulk-write-mixed-collection + + +# start-bulk-write-mixed-client +operations = [ + InsertOne( + namespace="sample_mflix.movies", + document={ + "title": "Minari", + "runtime": 217, + "genres": ["Drama", "Comedy"] + } + ), + UpdateOne( + namespace="sample_mflix.movies", + filter={ "title": "Minari" }, + update={ "$set": { "runtime": 117 }} + ), + DeleteMany( + namespace="sample_restaurants.restaurants", + filter={ "cuisine": "French" } + ) +] + +results = await client.bulk_write(operations) + +print(results) +# end-bulk-write-mixed-client + +# start-bulk-write-unordered +results = await restaurants.bulk_write(operations, ordered=False) +# end-bulk-write-unordered + +# start-bulk-write-verbose +results = await client.bulk_write(operations, verbose_results=True) +# end-bulk-write-verbose \ No newline at end of file diff --git a/source/includes/write/delete-async.py b/source/includes/write/delete-async.py new file mode 100644 index 00000000..f2005980 --- /dev/null +++ b/source/includes/write/delete-async.py @@ -0,0 +1,25 @@ +# start-delete-one +query_filter = { "name": "Ready Penny Inn" } + +result = await restaurants.delete_one(query_filter) +# end-delete-one + +# start-delete-many +query_filter = { "borough": "Brooklyn" } + +result = await restaurants.delete_many(query_filter) +# end-delete-many + +# start-delete-many-collation +from pymongo.collation import Collation + +query_filter = { "borough": "Brooklyn" } + +result = await restaurants.delete_many(query_filter, collation=Collation(locale='fr_CA')) +# end-delete-many-collation + +# start-delete-options +query_filter = { 'name': {'$regex': 'Mongo' }} + +result = await restaurants.delete_many(query_filter, comment="Deleting Mongo restaurants") +# end-delete-options \ No newline at end of file diff --git a/source/includes/write/transaction-async.py b/source/includes/write/transaction-async.py new file mode 100644 index 00000000..3855fee4 --- /dev/null +++ b/source/includes/write/transaction-async.py @@ -0,0 +1,35 @@ +# start-transaction +# Establishes a connection to the MongoDB server +client = AsyncMongoClient("") + +# Defines the database and collection +restaurants_db = client["sample_restaurants"] +restaurants_collection = restaurants_db["restaurants"] + +# Function performs the transaction +async def insert_documents(session): + restaurants_collection_with_session = restaurants_collection.with_options( + write_concern=WriteConcern("majority"), + read_concern=ReadConcern("local") + ) + + # Inserts documents within the transaction + await restaurants_collection_with_session.insert_one( + {"name": "PyMongo Pizza", "cuisine": "Pizza"}, session=session + ) + await restaurants_collection_with_session.insert_one( + {"name": "PyMongo Burger", "cuisine": "Burger"}, session=session + ) + +# Starts a client session +with client.start_session() as session: + try: + # Uses the with_transaction method to start a transaction, execute the callback, and commit (or abort on error). + await session.with_transaction(insert_documents) + print("Transaction succeeded") + except (ConnectionFailure, OperationFailure) as e: + print(f"Transaction failed: {e}") + +# Closes the client connection +await client.close() +# end-transaction \ No newline at end of file diff --git a/source/includes/write/transaction.py b/source/includes/write/transaction.py index 7a9a0600..dd5a0b1c 100644 --- a/source/includes/write/transaction.py +++ b/source/includes/write/transaction.py @@ -22,7 +22,7 @@ def insert_documents(session): ) # Starts a client session -with client.start_session() as session: +async with client.start_session() as session: try: # Uses the with_transaction method to start a transaction, execute the callback, and commit (or abort on error). session.with_transaction(insert_documents) diff --git a/source/includes/write/update-async.py b/source/includes/write/update-async.py new file mode 100644 index 00000000..d8165557 --- /dev/null +++ b/source/includes/write/update-async.py @@ -0,0 +1,46 @@ +# start-update-one +restaurants = database["restaurants"] + +query_filter = {'name' : 'Bagels N Buns'} +update_operation = { '$set' : + { 'name' : '2 Bagels 2 Buns' } +} + +result = await restaurants.update_one(query_filter, update_operation) +# end-update-one + +# start-update-many +restaurants = database["restaurants"] + +query_filter = {'cuisine' : 'Pizza'} +update_operation = { '$set' : + { 'cuisine' : 'Pasta' } +} + +result = await restaurants.update_many(query_filter, update_operation) +# end-update-many + +# start-update-many-collation +from pymongo.collation import Collation + +restaurants = database["restaurants"] + +query_filter = {'cuisine' : 'Pizza'} +update_operation = { '$set' : + { 'cuisine' : 'Pasta' } +} + +result = await restaurants.update_many(query_filter, update_operation, + collation=Collation(locale='fr_CA')) +# end-update-many-collation + +# start-update-options +restaurants = database["restaurants"] + +query_filter = {'borough' : 'Manhattan'} +update_operation = { '$set' : + { 'borough' : 'Manhattan (north)' } +} + +result = await restaurants.update_many(query_filter, update_operation, upsert = True) +# end-update-options \ No newline at end of file