From cb2e5b97962a3bcbd55e60c41672e992ddd68e70 Mon Sep 17 00:00:00 2001 From: rustagir Date: Thu, 3 Apr 2025 11:49:32 -0400 Subject: [PATCH 1/4] DOCSP-46108: merge coll/client BW pages --- .../crud/write-operations/bulk-write.txt | 546 +++++++++++++++--- .../fundamentals/code-examples/BulkWrite.cs | 88 ++- .../code-examples/CollectionBulkWrite.cs | 157 +++++ 3 files changed, 674 insertions(+), 117 deletions(-) create mode 100644 source/includes/fundamentals/code-examples/CollectionBulkWrite.cs diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/fundamentals/crud/write-operations/bulk-write.txt index 4df46aa6..ee1f1a4a 100644 --- a/source/fundamentals/crud/write-operations/bulk-write.txt +++ b/source/fundamentals/crud/write-operations/bulk-write.txt @@ -15,27 +15,400 @@ Bulk Write Operations :values: reference .. meta:: - :keywords: insert, update, replace, code example + :keywords: insert, update, replace, code example, multiple changes Overview -------- -This guide shows you how to use the {+driver-short+} to perform **bulk write operations** -from your ``MongoClient`` instance. A bulk write operation is a single database call -that performs multiple write operations on one or more MongoDB collections. This is more -efficient than performing multiple individual write operations because it reduces the -number of round trips between your application and the database. +In this guide, you can learn how to perform multiple write operations in +a single database call by using **bulk write operations**. + +Consider a scenario in which you want to insert a document, +update multiple other documents, then delete a document. If you use +individual methods, each operation requires its own database call. + +By using a bulk write operation, you can perform multiple write operations in +fewer database calls. You can perform bulk write operations at the following levels: + +- :ref:`Collection `: You can use the + ``IMongoCollection.BulkWrite()`` or + ``IMongoCollection.BulkWriteAsync()`` method to perform bulk write + operations on a single collection. These methods make a database call + for each type of write operation. For example, the methods perform + multiple update operations in one call, but make two separate calls to + the database for an insert operation and a replace operation. + +- :ref:`Client `: If your application connects to + {+mdb-server+} version 8.0 or later, you can use the ``IMongoClient.BulkWrite()`` + or ``IMongoClient.BulkWriteAsync()`` method to perform bulk write + operations on multiple collections and databases in the same cluster. + This method performs all write operations in one database call. Sample Data ~~~~~~~~~~~ -The examples in this guide use the ``sample_restaurants.restaurants`` collection -from the :atlas:`Atlas sample datasets `. To learn how to create a -free MongoDB Atlas cluster and load the sample datasets, see the -:ref:`` tutorial. +The examples in this guide use the ``sample_restaurants.restaurants`` +and ``sample_mflix.movies`` collections from the :atlas:`Atlas sample +datasets `. To learn how to create a free MongoDB Atlas +cluster and load the sample datasets, see the :atlas:`Get Started with +Atlas ` guide. + +.. tip:: Bulk Write Operations with POCOs + + The examples in this guide use the ``BsonDocument`` type for the ``TDocument`` type + in all generic classes. You can also use a Plain Old CLR Object (POCO) for these + classes. To do so, you must define a class that represents the documents in your + collection. The class must have properties that match the fields in your documents. + For more information, see :ref:`csharp-poco`. + +.. _csharp-coll-bulk-write: + +Collection Bulk Write +--------------------- + +Bulk write operations contain one or more write operations. For each +write operation you want to perform, create an instance of one of +the following ``WriteModel`` classes: + +- ``DeleteManyModel`` +- ``DeleteOneModel`` +- ``InsertOneModel`` +- ``ReplaceOneModel`` +- ``UpdateManyModel`` +- ``UpdateOneModel`` + +The following sections show how to create and use instances of the preceding classes +to perform the corresponding write operation in a bulk write +operation. The :ref:`csharp-coll-bulkwrite-method` section +demonstrates how to pass a list of models to the ``BulkWrite()`` or +``BulkWriteAsync()`` method to perform the bulk operation. + +Insert Operations +~~~~~~~~~~~~~~~~~ + +To perform an insert operation, create an ``InsertOneModel`` +instance and specify the document you want to insert. + +The following example creates an instance of the +``InsertOneModel`` class. This instance directs the driver to +insert a document in which the ``"name"`` field is ``"Mongo's Deli"`` +into the ``restaurants`` collection. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-insert-one + :end-before: end-insert-one + :language: csharp + :copyable: + :dedent: + +To insert multiple documents, create an instance of ``InsertOneModel`` +for each document. + +.. important:: Duplicate Key Error + + When performing a bulk operation, the ``InsertOneModel`` cannot + insert a document with an ``_id`` that already exists in the + collection. In this situation, the driver throws a + ``MongoBulkWriteException``. + +Update Operations +~~~~~~~~~~~~~~~~~ + +To update a single document, create an instance of +``UpdateOneModel`` and pass the following arguments: + +- **Query filter** that specifies the criteria used to match documents + in your collection. To learn more about specifying a query, see + :manual:`Query and Projection Operators + ` in the {+mdb-server+} manual. + +- **Update document** that describes the update to perform. To learn + more about specifying an update, see :manual:`Update Operators + ` in the {+mdb-server+} manual. + +An ``UpdateOneModel`` instance specifies an update for *the first* +document that matches your query filter. + +In the following code example, the ``UpdateOneModel`` object +represents an update operation on the ``restaurants`` collection. +The operation matches the first document in the collection where the value of the ``name`` +field is ``"Mongo's Deli"``. It then updates the value of the ``cuisine`` field in the +matched document to ``"Sandwiches and Salads"``. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-update-one + :end-before: end-update-one + :language: csharp + :copyable: + :dedent: + +To update multiple documents, create an instance of ``UpdateManyModel`` and pass +the same arguments as for ``UpdateOneModel``. The ``UpdateManyModel`` +class specifies updates for *all* documents that match your query +filter. + +In the following code example, the ``UpdateManyModel`` object +represents an update operation on the ``restaurants`` collection. +The operation matches all documents in the collection where +the value of the ``name`` field is ``"Mongo's Deli"``. It then updates +the value of the ``cuisine`` field to ``"Sandwiches and Salads"``. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-update-many + :end-before: end-update-many + :language: csharp + :copyable: + :dedent: + +Replace Operations +~~~~~~~~~~~~~~~~~~ + +A replace operation removes all fields and values of a specified document and +replaces them with new fields and values that you specify. To perform a +replace operation, create an instance of ``ReplaceOneModel`` and pass a +query filter and the fields and values you want to replace the matching +document with. + +In the following example, the ``ReplaceOneModel`` object +represents a replace operation on the ``restaurants`` collection. +The operation matches the document in the collection +where the value of the ``restaurant_id`` field is ``"1234"``. It then +removes all fields other than ``_id`` from this document, and sets new values in the +``name``, ``cuisine``, ``borough``, and ``restaurant_id`` fields. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-replace-one + :end-before: end-replace-one + :language: csharp + :copyable: + :dedent: + +To replace multiple documents, you must create an instance of +``ReplaceOneModel`` for each document. + +Delete Operations +~~~~~~~~~~~~~~~~~ + +To delete a document, create an instance of ``DeleteOneModel`` and pass a +query filter specifying the document you want to delete. A +``DeleteOneModel`` instance provides instructions to delete +only *the first* document that matches your query filter. + +In the following code example, the ``DeleteOneModel`` object +represents a delete operation on the ``restaurants`` collection. +The operation matches and deletes the first document +where the value of the ``restaurant_id`` field is ``"5678"``. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-delete-one + :end-before: end-delete-one + :language: csharp + :copyable: + :dedent: + +To delete multiple documents, create an instance of ``DeleteManyModel`` and pass a +query filter specifying the documents you want to delete. An instance of +``DeleteManyModel`` provides instructions to remove *all* documents that +match your query filter. + +In the following code example, the ``DeleteManyModel`` object +represents a delete operation on the ``restaurants`` collection. +The operation matches and deletes all documents +where the value of the ``name`` field is ``"Mongo's Deli"``. + +.. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-delete-many + :end-before: end-delete-many + :language: csharp + :copyable: + :dedent: + +.. _csharp-coll-bulkwrite-method: + +Perform the Bulk Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After you define a ``WriteModel`` instance for each operation that you want to perform, +create an instance of a class that implements the ``IEnumerable`` interface. Add your +``WriteModel`` objects to this ``IEnumerable``, then pass the ``IEnumerable`` +to the ``BulkWrite()`` or ``BulkWriteAsync()`` method. By default, these methods run +the operations in the order they're defined in the list. + +.. tip:: IEnumerable + + ``Array`` and ``List`` are two common classes that implement the + ``IEnumerable`` interface. + +Select from the following tabs to view how to use the synchronous ``BulkWrite()`` method +and the asynchronous ``BulkWriteAsync()`` method to perform a bulk write +operation on the ``restaurants`` collection: + +.. tabs:: + + .. tab:: Synchronous + :tabid: bulk-write-sync + + .. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-bulk-write-sync + :end-before: end-bulk-write-sync + :language: csharp + :copyable: + :dedent: + + .. tab:: Asynchronous + :tabid: bulk-write-async + + .. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-bulk-write-async + :end-before: end-bulk-write-async + :language: csharp + :copyable: + :dedent: + +The preceding code examples produce the following output: + +.. code-block:: shell + :copyable: false + + MongoDB.Driver.BulkWriteResult1+Acknowledged[MongoDB.Bson.BsonDocument] + +.. note:: + + When the driver runs a bulk operation, it uses the write concern of the + target collection. The driver reports all write concern errors after + attempting all operations, regardless of execution order. + +Customize Bulk Write Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When you call the ``BulkWrite()`` or ``BulkWriteAsync()`` method, you can pass an +instance of the ``BulkWriteOptions`` class. The ``BulkWriteOptions`` class +contains the following properties, which represent options you can use to configure the +bulk write operation: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``BypassDocumentValidation`` + - | Specifies whether the operation bypasses document-level validation. For more + information, see :manual:`Schema + Validation ` in the {+mdb-server+} + manual. + | Defaults to ``False``. + + * - ``Comment`` + - | A comment to attach to the operation, in the form of a ``BsonValue``. For + more information, see the :manual:`delete command + fields ` guide in the + {+mdb-server+} manual. + + * - ``IsOrdered`` + - | If ``True``, the driver performs the write operations in the order + provided. If an error occurs, the remaining operations are not + attempted. + | + | If ``False``, the driver performs the operations in an + arbitrary order and attempts to perform all operations. If any of the write + operations in an unordered bulk write fail, the driver + reports the errors only after attempting all operations. + | Defaults to ``True``. -Define the Write Operations ---------------------------- + * - ``Let`` + - | A map of parameter names and values, in the form of a ``BsonDocument``. Values + must be constant or closed + expressions that don't reference document fields. For more information, + see the :manual:`let statement + ` in the + {+mdb-server+} manual. + +The following code examples use a ``BulkWriteOptions`` object to perform +an unordered bulk write operation: + +.. tabs:: + + .. tab:: Synchronous + :tabid: bulk-write-options-sync + + .. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-bulk-write-options-sync + :end-before: end-bulk-write-options-sync + :language: csharp + :copyable: + :dedent: + + .. tab:: Asynchronous + :tabid: bulk-write-options-async + + .. literalinclude:: /includes/fundamentals/code-examples/CollectionBulkWrite.cs + :start-after: start-bulk-write-options-async + :end-before: end-bulk-write-options-async + :language: csharp + :copyable: + :dedent: + +Return Value +~~~~~~~~~~~~ + +The ``BulkWrite()`` and ``BulkWriteAsync()`` methods return a +``BulkWriteResult`` object that contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``IsAcknowledged`` + - | Indicates whether the server acknowledged the bulk write operation. If the + value of this property is ``False`` and you try to access any other property + of the ``BulkWriteResult`` object, the driver throws an exception. + + * - ``DeletedCount`` + - | The number of documents deleted, if any. + + * - ``InsertedCount`` + - | The number of documents inserted, if any. + + * - ``MatchedCount`` + - | The number of documents matched for an update, if applicable. + + * - ``ModifiedCount`` + - | The number of documents modified, if any. + + * - ``IsModifiedCountAvailable`` + - | Indicates whether the modified count is available. + + * - ``Upserts`` + - | A list that contains information about each request that + resulted in an upsert operation. + + * - ``RequestCount`` + - | The number of requests in the bulk operation. + +Handling Exceptions +~~~~~~~~~~~~~~~~~~~ + +If any of the operations in a bulk write operation fail, the {+driver-short+} throws a +``BulkWriteError`` and does not perform any further operations. + +A ``BulkWriteError`` object contains the ``Index`` property that +describes the index of the request that resulted in an error. + +.. _csharp-client-bulk-write: + +Client Bulk Write +----------------- + +When connecting to a deployment running {+mdb-server+} 8.0 or later, +you can use the ``IMongoClient.BulkWrite()`` or +``IMongoClient.BulkWriteAsync()`` method method to write +to multiple databases and collections in the same cluster. These +methods perform all write operations in a single call. For each write operation you want to perform, create an instance of one of the following ``BulkWriteModel`` classes: @@ -47,23 +420,19 @@ the following ``BulkWriteModel`` classes: - ``BulkWriteDeleteOneModel`` - ``BulkWriteDeleteManyModel`` -The following sections show how to create and use instances of the preceding classes -to perform the corresponding write operation in a bulk write. - -.. tip:: Bulk Write Operations with POCOs - - The examples in this guide use the ``BsonDocument`` type for the ``TDocument`` type - in all generic classes. You can also use a Plain Old CLR Object (POCO) for these - classes. To do so, you must define a class that represents the documents in your - collection. The class must have properties that match the fields in your documents. - For more information, see :ref:``. +The following sections show how to create and use instances of the +preceding classes to perform the corresponding write operation in a bulk +write.The :ref:`csharp-client-bulkwrite-method` section +demonstrates how to pass a list of models to the ``BulkWrite()`` or +``BulkWriteAsync()`` method to perform the bulk operation. Insert Operations ~~~~~~~~~~~~~~~~~ To perform an insert operation, create an instance of the ``BulkWriteInsertOneModel`` class. -The ``BulkWriteInsertOneModel`` constructor accepts the following parameters: +The ``BulkWriteInsertOneModel`` constructor accepts the +following parameters: .. list-table:: :header-rows: 1 @@ -82,21 +451,16 @@ The ``BulkWriteInsertOneModel`` constructor accepts the following par | | **Data Type:** ``TDocument`` -The following example creates an instance of the ``BulkWriteInsertOneModel`` -class. This instance directs the driver to insert a document in which the ``"name"`` field -is ``"Mongo's Deli"`` into the ``sample_restaurants.restaurants`` collection. +The following example creates instances of the ``BulkWriteInsertOneModel`` +class. These instances direct the driver to insert documents into the +``sample_restaurants.restaurants`` and ``sample_mflix.movies`` collections. .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs :start-after: start-bulk-insert-one :end-before: end-bulk-insert-one :language: csharp :copyable: - :dedent: 8 - -.. tip:: Insert Multiple Documents - - To insert multiple documents, create an instance of the - ``BulkWriteInsertOneModel`` class for each document you want to insert. + :dedent: Update Operations ~~~~~~~~~~~~~~~~~ @@ -163,18 +527,16 @@ parameters: | **Data Type:** `IEnumerable `__ | **Default:** ``null`` -In the following code example, the ``BulkWriteUpdateOneModel`` object -represents an update operation on the ``sample_restaurants.restaurants`` collection. -The operation matches the first document in the collection where the value of the ``name`` -field is ``"Mongo's Deli"``. It then updates the value of the ``cuisine`` field in the -matched document to ``"Sandwiches and Salads"``. +In the following code example, the ``BulkWriteUpdateOneModel`` objects +represent update operations on the ``sample_restaurants.restaurants`` +and ``sample_mflix.movies`` collections. .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs :start-after: start-bulk-update-one :end-before: end-bulk-update-one :language: csharp :copyable: - :dedent: 8 + :dedent: To update multiple documents, create an instance of the ``BulkWriteUpdateManyModel`` class. The constructor for this class @@ -185,15 +547,15 @@ operation updates *all documents* that match your query filter. In the following code example, the ``BulkWriteUpdateManyModel`` object represents an update operation on the ``sample_restaurants.restaurants`` collection. The operation matches all documents in the collection where -the value of the ``name`` field is ``"Mongo's Deli"``. It then updates -the value of the ``cuisine`` field to ``"Sandwiches and Salads"``. +the value of the ``name`` field is ``"Starbucks"``. It then updates +the value of the ``cuisine`` field to ``"Coffee (Chain)"``. .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs :start-after: start-bulk-update-many :end-before: end-bulk-update-many :language: csharp :copyable: - :dedent: 8 + :dedent: Replace Operations ~~~~~~~~~~~~~~~~~~ @@ -252,24 +614,16 @@ constructor accepts the following parameters: | **Data Type:** {+bool-data-type+} | **Default:** ``false`` -In the following example, the ``BulkWriteReplaceOneModel`` object -represents a replace operation on the ``sample_restaurants.restaurants`` collection. -The operation matches the document in the collection -where the value of the ``restaurant_id`` field is ``"1234"``. It then -removes all fields other than ``_id`` from this document, and sets new values in the -``name``, ``cuisine``, ``borough``, and ``restaurant_id`` fields. +In the following example, the ``BulkWriteReplaceOneModel`` objects +represent replace operations on the ``sample_restaurants.restaurants`` +and ``sample_mflix.movies`` collections. .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs :start-after: start-bulk-replace-one :end-before: end-bulk-replace-one :language: csharp :copyable: - :dedent: 8 - -.. tip:: Replace Multiple Documents - - To replace multiple documents, create an instance of the - ``BulkWriteReplaceOneModel`` class for each document you want to replace. + :dedent: Delete Operations ~~~~~~~~~~~~~~~~~ @@ -313,17 +667,16 @@ parameters: | **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ | **Default:** ``null`` -In the following code example, the ``BulkWriteDeleteOneModel`` object -represents a delete operation on the ``sample_restaurants.restaurants`` collection. -The operation matches and deletes the first document -where the value of the ``restaurant_id`` field is ``"5678"``. +In the following code example, the ``BulkWriteDeleteOneModel`` objects +represent delete operations on the ``sample_restaurants.restaurants`` +and ``sample_mflix.movies`` collections. .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs :start-after: start-bulk-delete-one :end-before: end-bulk-delete-one :language: csharp :copyable: - :dedent: 8 + :dedent: To delete multiple documents, create an instance of the ``BulkWriteDeleteManyModel`` class and pass a query filter that specifies the document that you want to delete. @@ -340,10 +693,12 @@ where the value of the ``name`` field is ``"Mongo's Deli"``. :end-before: end-bulk-delete-many :language: csharp :copyable: - :dedent: 8 + :dedent: + +.. _csharp-client-bulkwrite-method: -Run the Write Operations ------------------------- +Perform the Bulk Operation +~~~~~~~~~~~~~~~~~~~~~~~~~~ After you define a ``BulkWriteModel`` instance for each operation that you want to perform, create an instance of a class that implements the ``IReadOnlyList`` interface. Add your @@ -357,7 +712,8 @@ the operations in the order they're defined in the collection. interface. Select from the following tabs to view how to use the synchronous ``BulkWrite()`` method -and the asynchronous ``BulkWriteAsync()`` method to perform a bulk write operation. +and the asynchronous ``BulkWriteAsync()`` method to perform a bulk write +operation on multiple namespaces. .. tabs:: @@ -369,7 +725,7 @@ and the asynchronous ``BulkWriteAsync()`` method to perform a bulk write operati :end-before: end-bulk-write-sync :language: csharp :copyable: - :dedent: 8 + :dedent: .. tab:: Asynchronous :tabid: bulk-write-async @@ -379,7 +735,7 @@ and the asynchronous ``BulkWriteAsync()`` method to perform a bulk write operati :end-before: end-bulk-write-async :language: csharp :copyable: - :dedent: 8 + :dedent: The preceding code examples produce the following output: @@ -387,8 +743,10 @@ The preceding code examples produce the following output: BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True) -Customize Bulk Write Operations -------------------------------- +.. _csharp-client-bulk-write-options: + +Customize Bulk Write +~~~~~~~~~~~~~~~~~~~~ When you call the ``BulkWrite()`` or ``BulkWriteAsync()`` method, you can pass an instance of the ``ClientBulkWriteOptions`` class. The ``ClientBulkWriteOptions`` class @@ -444,8 +802,8 @@ bulk write operation: enum. | Defaults to the write concern of the collection on which the operation is running. -The following code examples use a ``ClientBulkWriteOptions`` object to customize -a delete operation: +The following code examples use a ``ClientBulkWriteOptions`` object to +customize the bulk write operation: .. tabs:: @@ -457,7 +815,7 @@ a delete operation: :end-before: end-bulk-write-options-sync :language: csharp :copyable: - :dedent: 8 + :dedent: .. tab:: Asynchronous :tabid: bulk-write-options-async @@ -467,10 +825,10 @@ a delete operation: :end-before: end-bulk-write-options-async :language: csharp :copyable: - :dedent: 8 + :dedent: Return Value ------------- +~~~~~~~~~~~~ The ``BulkWrite()`` and ``BulkWriteAsync()`` methods return a ``ClientBulkWriteResult`` object that contains the following properties: @@ -515,7 +873,7 @@ object that contains the following properties: - | The number of documents upserted, if any. Handling Exceptions -------------------- +~~~~~~~~~~~~~~~~~~~ If any of the operations in a bulk write operation fail, the {+driver-short+} throws a ``ClientBulkWriteException`` and does not perform any further operations. @@ -566,17 +924,33 @@ To learn how to perform individual write operations, see the following guides: To learn more about any of the methods or types discussed in this guide, see the following API documentation: -- `BulkWrite() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.BulkWrite.html>`__ -- `BulkWriteAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.BulkWriteAsync.html>`__ -- `ClientBulkWriteOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteOptions.html>`__ -- `ClientBulkWriteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteResult.html>`__ -- `BulkWriteInsertOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteInsertOneModel-1.html>`__ -- `BulkWriteUpdateOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateOneModel-1.html>`__ -- `BulkWriteUpdateManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateManyModel-1.html>`__ -- `BulkWriteReplaceOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteReplaceOneModel-1.html>`__ -- `BulkWriteDeleteOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteOneModel-1.html>`__ -- `BulkWriteDeleteManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteManyModel-1.html>`__ -- `BulkWriteInsertOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteInsertOneResult.html>`__ -- `BulkWriteUpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateResult.html>`__ -- `BulkWriteDeleteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteResult.html>`__ -- `ClientBulkWriteException <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteException.html>`__ +- Collection Bulk Write + + - `BulkWrite() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.BulkWrite.html>`__ + - `BulkWriteAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.BulkWriteAsync.html>`__ + - `BulkWriteOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteOptions.-ctor.html>`__ + - `BulkWriteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteResult.html>`__ + - `InsertOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.InsertOneModel-1.html>`__ + - `UpdateOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateOneModel-1.html>`__ + - `UpdateManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateManyModel-1.html>`__ + - `ReplaceOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOneModel-1.html>`__ + - `DeleteOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.DeleteOneModel-1.html>`__ + - `DeleteManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.DeleteManyModel-1.html>`__ + - `BulkWriteError <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteError.html>`__ + +- Client Bulk Write + + - `BulkWrite() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.BulkWrite.html>`__ + - `BulkWriteAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.BulkWriteAsync.html>`__ + - `ClientBulkWriteOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteOptions.html>`__ + - `ClientBulkWriteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteResult.html>`__ + - `BulkWriteInsertOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteInsertOneModel-1.html>`__ + - `BulkWriteUpdateOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateOneModel-1.html>`__ + - `BulkWriteUpdateManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateManyModel-1.html>`__ + - `BulkWriteReplaceOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteReplaceOneModel-1.html>`__ + - `BulkWriteDeleteOneModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteOneModel-1.html>`__ + - `BulkWriteDeleteManyModel <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteManyModel-1.html>`__ + - `BulkWriteInsertOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteInsertOneResult.html>`__ + - `BulkWriteUpdateResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteUpdateResult.html>`__ + - `BulkWriteDeleteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BulkWriteDeleteResult.html>`__ + - `ClientBulkWriteException <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteException.html>`__ diff --git a/source/includes/fundamentals/code-examples/BulkWrite.cs b/source/includes/fundamentals/code-examples/BulkWrite.cs index 4ee5e0c6..bfea7a3d 100644 --- a/source/includes/fundamentals/code-examples/BulkWrite.cs +++ b/source/includes/fundamentals/code-examples/BulkWrite.cs @@ -5,7 +5,7 @@ class BulkWrite static void InsertOne() { // start-bulk-insert-one - var insertOneModel = new BulkWriteInsertOneModel( + var restaurantToInsert = new BulkWriteInsertOneModel( "sample_restaurants.restaurants", new BsonDocument{ { "name", "Mongo's Deli" }, @@ -14,17 +14,31 @@ static void InsertOne() { "restaurant_id", "1234" } } ); + + var movieToInsert = new BulkWriteInsertOneModel( + "sample_mflix.movies", + new BsonDocument{ + { "name", "Silly Days" }, + { "year", 2022 } + } + ); // end-bulk-insert-one } static void UpdateOne() { // start-bulk-update-one - var updateOneModel = new BulkWriteUpdateOneModel( + var restaurantUpdate = new BulkWriteUpdateOneModel( "sample_restaurants.restaurants", Builders.Filter.Eq("name", "Mongo's Deli"), Builders.Update.Set("cuisine", "Sandwiches and Salads") ); + + var movieUpdate = new BulkWriteUpdateOneModel( + "sample_mflix.movies", + Builders.Filter.Eq("name", "Carrie"), + Builders.Update.Set("seen", True) + ); // end-bulk-update-one } @@ -33,8 +47,8 @@ static void UpdateMany() // start-bulk-update-many var updateManyModel = new BulkWriteUpdateManyModel( "sample_restaurants.restaurants", - Builders.Filter.Eq("name", "Mongo's Deli"), - Builders.Update.Set("cuisine", "Sandwiches and Salads") + Builders.Filter.Eq("name", "Starbucks"), + Builders.Update.Set("cuisine", "Coffee (Chain)") ); // end-bulk-update-many } @@ -42,7 +56,7 @@ static void UpdateMany() static void ReplaceOne() { // start-bulk-replace-one - var replaceOneModel = new BulkWriteReplaceOneModel( + var restaurantReplacement = new BulkWriteReplaceOneModel( "sample_restaurants.restaurants", Builders.Filter.Eq("restaurant_id", "1234"), new BsonDocument{ @@ -52,16 +66,30 @@ static void ReplaceOne() { "restaurant_id", "5678" } } ); + + var movieReplacement = new BulkWriteReplaceOneModel( + "sample_mflix.movies", + Builders.Filter.Eq("movie_id", "4004"), + new BsonDocument{ + { "name", "Loving Sylvie" }, + { "year", 1999 } + } + ); // end-bulk-replace-one } static void DeleteOne() { // start-bulk-delete-one - var deleteOneModel = new BulkWriteDeleteOneModel( + var restaurantToDelete = new BulkWriteDeleteOneModel( "sample_restaurants.restaurants", Builders.Filter.Eq("restaurant_id", "5678") ); + + var movieToDelete = new BulkWriteDeleteOneModel( + "sample_mflix.movies", + Builders.Filter.Eq("movie_id", "4687") + ); // end-bulk-delete-one } @@ -79,12 +107,13 @@ static void BulkWriteSync() { // start-bulk-write-sync var client = new MongoClient("mongodb://localhost:27017"); - var collection = "sample_restaurants.restaurants"; + var restaurantNamespace = "sample_restaurants.restaurants"; + var movieNamespace = "sample_mflix.movies"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel( - collection, + restaurantNamespace, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, @@ -93,39 +122,38 @@ static void BulkWriteSync() } ), new BulkWriteInsertOneModel( - collection, + movieNamespace, new BsonDocument{ - { "name", "Mongo's Deli" }, - { "cuisine", "Sandwiches" }, - { "borough", "Brooklyn" }, - { "restaurant_id", "5678" } + { "name", "Sarah's Secret" }, + { "year", 1988 } } ), new BulkWriteUpdateManyModel( - collection, + restaurantNamespace, Builders.Filter.Eq("name", "Mongo's Deli"), Builders.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel( - collection, - Builders.Filter.Eq("restaurant_id", "1234") + movieNamespace, + Builders.Filter.Eq("movie_id", "7888") ) }; - var results = client.BulkWrite(bulkWriteModels); - Console.WriteLine("Bulk write results: " + results); + var result = client.BulkWrite(bulkWriteModels); + Console.WriteLine(result); // end-bulk-write-sync } static async Task BulkWriteAsync() { // start-bulk-write-async var client = new MongoClient("mongodb://localhost:27017"); - var collection = "sample_restaurants.restaurants"; + var restaurantNamespace = "sample_restaurants.restaurants"; + var movieNamespace = "sample_mflix.movies"; var bulkWriteModels = new[] { new BulkWriteInsertOneModel( - collection, + restaurantNamespace, new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, @@ -134,27 +162,25 @@ static async Task BulkWriteAsync() } ), new BulkWriteInsertOneModel( - collection, + movieNamespace, new BsonDocument{ - { "name", "Mongo's Deli" }, - { "cuisine", "Sandwiches" }, - { "borough", "Brooklyn" }, - { "restaurant_id", "5678" } + { "name", "Sarah's Secret" }, + { "year", 1988 } } ), new BulkWriteUpdateManyModel( - collection, + restaurantNamespace, Builders.Filter.Eq("name", "Mongo's Deli"), Builders.Update.Set("cuisine", "Sandwiches and Salads") ), new BulkWriteDeleteOneModel( - collection, - Builders.Filter.Eq("restaurant_id", "1234") + movieNamespace, + Builders.Filter.Eq("movie_id", "7888") ) }; - var results = await client.BulkWriteAsync(bulkWriteModels); - Console.WriteLine("Bulk write results: " + results); + var result = await client.BulkWriteAsync(bulkWriteModels); + Console.WriteLine(result); // end-bulk-write-async } @@ -198,4 +224,4 @@ static async Task BulkWriteOptionsAsync() var results = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions); // end-bulk-write-options-async } -} \ No newline at end of file +} diff --git a/source/includes/fundamentals/code-examples/CollectionBulkWrite.cs b/source/includes/fundamentals/code-examples/CollectionBulkWrite.cs new file mode 100644 index 00000000..59df03da --- /dev/null +++ b/source/includes/fundamentals/code-examples/CollectionBulkWrite.cs @@ -0,0 +1,157 @@ +using MongoDB.Driver; +using MongoDB.Bson; + +var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI"); +if (connectionString == null) +{ + Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/docs/drivers/csharp/current/quick-start/#set-your-connection-string"); + Environment.Exit(0); +} + +var client = new MongoClient(connectionString); +var collection = client.GetDatabase("db").GetCollection("rest"); + +// start-insert-one +var insertOneModel = new InsertOneModel( + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } +); +// end-insert-one + +// start-update-one +var updateOneModel = new UpdateOneModel( + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") +); +// end-update-one + +// start-update-many +var updateManyModel = new UpdateManyModel( + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") +); +// end-update-many + +// start-replace-one +var replaceOneModel = new ReplaceOneModel( + Builders.Filter.Eq("restaurant_id", "1234"), + new BsonDocument{ + { "name", "Mongo's Pizza" }, + { "cuisine", "Pizza" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } +); +// end-replace-one + +// start-delete-one +var deleteOneModel = new DeleteOneModel( + Builders.Filter.Eq("restaurant_id", "5678") +); +// end-delete-one + +// start-delete-many +var deleteManyModel = new DeleteManyModel( + Builders.Filter.Eq("name", "Mongo's Deli") +); +// end-delete-many + +// start-bulk-write-sync +var models = new List> +{ + new InsertOneModel( + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } + ), + new InsertOneModel( + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } + ), + new UpdateManyModel( + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") + ), + new DeleteOneModel( + Builders.Filter.Eq("restaurant_id", "1234") + ) +}; + +var results = collection.BulkWrite(models); +Console.WriteLine(results); +// end-bulk-write-sync + +// start-bulk-write-async +var models = new List> +{ + new InsertOneModel( + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } + ), + new InsertOneModel( + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } + ), + new UpdateManyModel( + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") + ), + new DeleteOneModel( + Builders.Filter.Eq("restaurant_id", "1234") + ) +}; + +var results = await collection.BulkWriteAsync(models); +Console.WriteLine(results); +// end-bulk-write-async + +// start-bulk-write-options-sync +var models = new List> +{ +new DeleteOneModel( + Builders.Filter.Eq("restaurant_id", "5678") +) +}; + +var options = new BulkWriteOptions +{ + IsOrdered = false, +}; + +collection.BulkWrite(models, options); +// end-bulk-write-options-sync + +// start-bulk-write-options-async +var models = new List> +{ +new DeleteOneModel( + Builders.Filter.Eq("restaurant_id", "5678") +) +}; + +var options = new BulkWriteOptions +{ + IsOrdered = false, +}; + +await collection.BulkWriteAsync(models, options); +// end-bulk-write-options-async From 4b5b94244499d1a2b85355e46517c38cb461ca12 Mon Sep 17 00:00:00 2001 From: rustagir Date: Thu, 3 Apr 2025 11:59:26 -0400 Subject: [PATCH 2/4] wip --- .../crud/write-operations/bulk-write.txt | 3 +++ .../fundamentals/code-examples/BulkWrite.cs | 16 ++++++++-------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/fundamentals/crud/write-operations/bulk-write.txt index ee1f1a4a..b70d240b 100644 --- a/source/fundamentals/crud/write-operations/bulk-write.txt +++ b/source/fundamentals/crud/write-operations/bulk-write.txt @@ -921,6 +921,9 @@ To learn how to perform individual write operations, see the following guides: - :ref:`csharp-insert-guide` - :ref:`csharp-delete-guide` +API Documentation +~~~~~~~~~~~~~~~~~ + To learn more about any of the methods or types discussed in this guide, see the following API documentation: diff --git a/source/includes/fundamentals/code-examples/BulkWrite.cs b/source/includes/fundamentals/code-examples/BulkWrite.cs index bfea7a3d..32168a41 100644 --- a/source/includes/fundamentals/code-examples/BulkWrite.cs +++ b/source/includes/fundamentals/code-examples/BulkWrite.cs @@ -18,7 +18,7 @@ static void InsertOne() var movieToInsert = new BulkWriteInsertOneModel( "sample_mflix.movies", new BsonDocument{ - { "name", "Silly Days" }, + { "title", "Silly Days" }, { "year", 2022 } } ); @@ -36,7 +36,7 @@ static void UpdateOne() var movieUpdate = new BulkWriteUpdateOneModel( "sample_mflix.movies", - Builders.Filter.Eq("name", "Carrie"), + Builders.Filter.Eq("title", "Carrie"), Builders.Update.Set("seen", True) ); // end-bulk-update-one @@ -69,7 +69,7 @@ static void ReplaceOne() var movieReplacement = new BulkWriteReplaceOneModel( "sample_mflix.movies", - Builders.Filter.Eq("movie_id", "4004"), + Builders.Filter.Eq("title", "Insomnia"), new BsonDocument{ { "name", "Loving Sylvie" }, { "year", 1999 } @@ -88,7 +88,7 @@ static void DeleteOne() var movieToDelete = new BulkWriteDeleteOneModel( "sample_mflix.movies", - Builders.Filter.Eq("movie_id", "4687") + Builders.Filter.Eq("title", "Mr. Nobody") ); // end-bulk-delete-one } @@ -135,7 +135,7 @@ static void BulkWriteSync() ), new BulkWriteDeleteOneModel( movieNamespace, - Builders.Filter.Eq("movie_id", "7888") + Builders.Filter.Eq("title", "House") ) }; @@ -175,7 +175,7 @@ static async Task BulkWriteAsync() ), new BulkWriteDeleteOneModel( movieNamespace, - Builders.Filter.Eq("movie_id", "7888") + Builders.Filter.Eq("title", "House") ) }; @@ -201,7 +201,7 @@ static void BulkWriteOptionsSync() VerboseResult = true }; - var results = client.BulkWrite(deleteOneModel, clientBulkWriteOptions); + var result = client.BulkWrite(deleteOneModel, clientBulkWriteOptions); // end-bulk-write-options-sync } static async Task BulkWriteOptionsAsync() @@ -221,7 +221,7 @@ static async Task BulkWriteOptionsAsync() VerboseResult = true }; - var results = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions); + var result = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions); // end-bulk-write-options-async } } From 30704be2e1cb261fa2166df94f8e8663d65b7ee1 Mon Sep 17 00:00:00 2001 From: rustagir Date: Thu, 3 Apr 2025 12:06:46 -0400 Subject: [PATCH 3/4] wip --- source/fundamentals/crud/write-operations.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index bb946729..4543bd96 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -15,7 +15,7 @@ Write Operations Update Many Replace Delete - Bulk Write Operations + Bulk Write - :ref:`csharp-insert-guide` - :ref:`csharp-update-one` From e093a94c6c21da6c1b18a48dc08bfd9c9712d99a Mon Sep 17 00:00:00 2001 From: rustagir Date: Fri, 4 Apr 2025 09:39:16 -0400 Subject: [PATCH 4/4] small fixes --- source/fundamentals/crud/write-operations/bulk-write.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/fundamentals/crud/write-operations/bulk-write.txt index b70d240b..f204f1fb 100644 --- a/source/fundamentals/crud/write-operations/bulk-write.txt +++ b/source/fundamentals/crud/write-operations/bulk-write.txt @@ -406,7 +406,7 @@ Client Bulk Write When connecting to a deployment running {+mdb-server+} 8.0 or later, you can use the ``IMongoClient.BulkWrite()`` or -``IMongoClient.BulkWriteAsync()`` method method to write +``IMongoClient.BulkWriteAsync()`` method to write to multiple databases and collections in the same cluster. These methods perform all write operations in a single call. @@ -422,7 +422,7 @@ the following ``BulkWriteModel`` classes: The following sections show how to create and use instances of the preceding classes to perform the corresponding write operation in a bulk -write.The :ref:`csharp-client-bulkwrite-method` section +write. The :ref:`csharp-client-bulkwrite-method` section demonstrates how to pass a list of models to the ``BulkWrite()`` or ``BulkWriteAsync()`` method to perform the bulk operation.