From 888aa9975aa3f692f0f32067ae06fc30f115310e Mon Sep 17 00:00:00 2001 From: Mike Woofter <108414937+mongoKart@users.noreply.github.com> Date: Wed, 30 Oct 2024 11:33:22 -0500 Subject: [PATCH] DOCSP-44422 - Bulk write API (#257) Co-authored-by: Rea Rustagi <85902999+rustagir@users.noreply.github.com> (cherry picked from commit 12fc8ef00817e2951e5976992eb6cd9590f0a81b) --- source/fundamentals/crud/write-operations.txt | 4 +- .../crud/write-operations/bulk-write.txt | 582 ++++++++++++++++++ .../fundamentals/code-examples/BulkWrite.cs | 201 ++++++ source/whats-new.txt | 3 + 4 files changed, 789 insertions(+), 1 deletion(-) create mode 100644 source/fundamentals/crud/write-operations/bulk-write.txt create mode 100644 source/includes/fundamentals/code-examples/BulkWrite.cs diff --git a/source/fundamentals/crud/write-operations.txt b/source/fundamentals/crud/write-operations.txt index 67fdd956..ec132498 100644 --- a/source/fundamentals/crud/write-operations.txt +++ b/source/fundamentals/crud/write-operations.txt @@ -13,7 +13,9 @@ Write Operations /fundamentals/crud/write-operations/insert /fundamentals/crud/write-operations/modify /fundamentals/crud/write-operations/delete + /fundamentals/crud/write-operations/bulk-write +- :ref:`csharp-insert-guide` - :ref:`csharp-change-guide` - :ref:`csharp-delete-guide` -- :ref:`csharp-insert-guide` +- :ref:`csharp-bulk-write` diff --git a/source/fundamentals/crud/write-operations/bulk-write.txt b/source/fundamentals/crud/write-operations/bulk-write.txt new file mode 100644 index 00000000..8da9b794 --- /dev/null +++ b/source/fundamentals/crud/write-operations/bulk-write.txt @@ -0,0 +1,582 @@ +.. _csharp-bulk-write: + +===================== +Bulk Write Operations +===================== + +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + +.. facet:: + :name: genre + :values: reference + +.. meta:: + :keywords: insert, update, replace, code example + +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. + +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. + +Define the Write Operations +--------------------------- + +For each write operation you want to perform, create an instance of one of +the following ``BulkWriteModel`` classes: + +- ``BulkWriteInsertOneModel`` +- ``BulkWriteUpdateOneModel`` +- ``BulkWriteUpdateManyModel`` +- ``BulkWriteReplaceOneModel`` +- ``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:``. + +Insert Operations +~~~~~~~~~~~~~~~~~ + +To perform an insert operation, create an instance of the +``BulkWriteInsertOneModel`` class. +The ``BulkWriteInsertOneModel`` constructor accepts the following parameters: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Parameter + - Description + + * - ``collectionNamespace`` + - | The database and collection to insert the BSON document into. + | + | **Data Type:** {+string-data-type+} or `CollectionNamespace <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html>`__ + + * - ``document`` + - | The document to insert into the collection. + | + | **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. + +.. 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. + +Update Operations +~~~~~~~~~~~~~~~~~ + +To update a single document, create an instance of the ``BulkWriteUpdateOneModel`` +class. The ``BulkWriteUpdateOneModel`` constructor accepts the following +parameters: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Parameter + - Description + + * - ``collectionNamespace`` + - | The database and collection to insert the BSON document into. + | + | **Data Type:** {+string-data-type+} or `CollectionNamespace <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html>`__ + + * - ``filter`` + - | The **query filter** that specifies the criteria used to match documents in your collection. + The ``UpdateOne`` operation updates *only the first document* that matches the + query filter. + | + | **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + + * - ``update`` + - | The update operation you want to perform. For more information about update + operations, see :manual:`Field Update Operators ` + in the {+mdb-server+} manual. + | + | **Data Type:** `UpdateDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.UpdateDefinition-1.html>`__ + + * - ``collation`` + - | *Optional.* The language collation to use when sorting results. See the + :manual:`{+mdb+server+} manual` + for more information. + | + | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + | **Default:** ``null`` + + * - ``hint`` + - | *Optional.* The index to use to scan for documents. + See the :manual:`{+mdb-server+} manual` + for more information. + | + | **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + | **Default:** ``null`` + + * - ``isUpsert`` + - | *Optional.* Specifies whether the update operation performs an upsert operation if no + documents match the query filter. See the :manual:`{+mdb-server+} manual` + for more information. + | + | **Data Type:** {+bool-data-type+} + | **Default:** ``false`` + + * - ``arrayFilters`` + - | Specifies which array elements to modify for an update operation on an array field. + See the :manual:`{+mdb-server+} manual` + for more information. + | + | **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"``. + +.. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-update-one + :end-before: end-bulk-update-one + :language: csharp + :copyable: + :dedent: 8 + +To update multiple documents, create an instance of the +``BulkWriteUpdateManyModel`` class. The constructor for this class +accepts the same parameters as the ``BulkWriteUpdateOneModel`` constructor. +The ``BulkWriteUpdateManyModel`` +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"``. + +.. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-update-many + :end-before: end-bulk-update-many + :language: csharp + :copyable: + :dedent: 8 + +Replace Operations +~~~~~~~~~~~~~~~~~~ + +To replace the fields in a document, create an instance of the +``BulkWriteReplaceOneModel`` class. The ``BulkWriteReplaceOneModel`` +constructor accepts the following parameters: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Parameter + - Description + + * - ``collectionNamespace`` + - | The database and collection to insert the BSON document into. + | + | **Data Type:** {+string-data-type+} or `CollectionNamespace <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html>`__ + + * - ``filter`` + - | The **query filter** that specifies the criteria used to match documents in your collection. + The ``UpdateOne`` operation updates *only the first document* that matches the + query filter. + | + | **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + + * - ``replacement`` + - | The replacement document, which specifies the fields and values to insert in the + target document. + | + | **Data Type:** ``TDocument`` + + * - ``collation`` + - | *Optional.* The language collation to use when sorting results. See + the :manual:`{+mdb-server+} manual` + for more information. + | + | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + | **Default:** ``null`` + + * - ``hint`` + - | *Optional.* The index to use to scan for documents. + See the :manual:`{+mdb-server+} manual` + for more information. + | + | **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__ + | **Default:** ``null`` + + * - ``isUpsert`` + - | *Optional.* Specifies whether the update operation performs an upsert operation if no + documents match the query filter. + See the :manual:`{+mdb-server+} manual` + for more information. + | + | **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. + +.. 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. + +Delete Operations +~~~~~~~~~~~~~~~~~ + +To delete a document, create an instance of the ``BulkWriteDeleteOneModel`` +class. The ``BulkWriteDeleteOneModel`` constructor accepts the following +parameters: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Parameter + - Description + + * - ``collectionNamespace`` + - | The database and collection to insert the BSON document into. + | + | **Data Type:** {+string-data-type+} or `CollectionNamespace <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.CollectionNamespace.html>`__ + + * - ``filter`` + - | The **query filter** that specifies the criteria used to match documents in your collection. + The ``DeleteOne`` operation deletes *only the first document* that matches the + query filter. + | + | **Data Type:** `FilterDefinition <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ + + * - ``collation`` + - | *Optional.* The language collation to use when sorting results. See + the :manual:`{+mdb-server+} manual` + for more information. + | + | **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__ + | **Default:** ``null`` + + * - ``hint`` + - | *Optional.* The index to use to scan for documents. + See the :manual:`{+mdb-server+} manual` + for more information. + | + | **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"``. + +.. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-delete-one + :end-before: end-bulk-delete-one + :language: csharp + :copyable: + :dedent: 8 + +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. +The ``DeleteMany`` operation removes *all documents* that match your +query filter. + +In the following code example, the ``BulkWriteDeleteManyModel`` object +represents a delete operation on the ``sample_restaurants.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/BulkWrite.cs + :start-after: start-bulk-delete-many + :end-before: end-bulk-delete-many + :language: csharp + :copyable: + :dedent: 8 + +Run the Write Operations +------------------------ + +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 +``BulkWriteModel`` objects to this ``IReadOnlyList``, then pass the ``IReadOnlyList`` +to the ``BulkWrite()`` or ``BulkWriteAsync()`` method. By default, these methods run +the operations in the order they're defined in the collection. + +.. tip:: IReadOnlyList + + ``Array`` and ``List`` are two common classes that implement the ``IReadOnlyList`` + interface. + +Select from the following tabs to view how to use the asynchronous +``BulkWriteAsync()`` method and the synchronous ``BulkWrite()`` method to +perform a bulk write operation. + +.. tabs:: + + .. tab:: Asynchronous + :tabid: bulk-write-async + + .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-write-async + :end-before: end-bulk-write-async + :language: csharp + :copyable: + :dedent: 8 + + .. tab:: Synchronous + :tabid: bulk-write-sync + + .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-write-sync + :end-before: end-bulk-write-sync + :language: csharp + :copyable: + :dedent: 8 + +The preceding code examples produce the following output: + +.. code-block:: shell + + BulkWriteResult({'writeErrors': [], 'writeConcernErrors': [], 'nInserted': 2, 'nUpserted': 0, 'nMatched': 2, 'nModified': 2, 'nRemoved': 1, 'upserted': []}, acknowledged=True) + +Customize Bulk Write Operations +------------------------------- + +When you call the ``BulkWrite()`` or ``BulkWriteAsync()`` method, you can pass an +instance of the ``ClientBulkWriteOptions`` class. The ``ClientBulkWriteOptions`` 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``. + + * - ``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. + + * - ``VerboseResult`` + - | Specifies whether the ``ClientBulkWriteResult`` object returned by the operation + includes detailed results for each successful write operation. + | Defaults to ``false``. + + * - ``WriteConcern`` + - | The write concern to use for the write operation, as a value from the ``WriteConcern`` + 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: + +.. tabs:: + + .. tab:: Asynchronous + :tabid: bulk-write-options-async + + .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-write-options-async + :end-before: end-bulk-write-options-async + :language: csharp + :copyable: + :dedent: 8 + + .. tab:: Synchronous + :tabid: bulk-write-options-sync + + .. literalinclude:: /includes/fundamentals/code-examples/BulkWrite.cs + :start-after: start-bulk-write-options-sync + :end-before: end-bulk-write-options-sync + :language: csharp + :copyable: + :dedent: 8 + +Return Value +------------ + +The ``BulkWrite()`` and ``BulkWriteAsync()`` methods return a ``ClientBulkWriteResult`` +object that contains the following properties: + +.. list-table:: + :widths: 30 70 + :header-rows: 1 + + * - Property + - Description + + * - ``Acknowledged`` + - | 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 ``ClientBulkWriteResult`` object, the driver throws an exception. + + * - ``DeleteResults`` + - | An ``IReadOnlyDictionary`` object containing the + results of each successful delete operation, if any. + + * - ``DeletedCount`` + - | The number of documents deleted, if any. + + * - ``InsertResults`` + - | An ``IReadOnlyDictionary`` object containing the + results of each successful insert operation, 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. + + * - ``UpsertResults`` + - | An ``IReadOnlyDictionary`` object containing the + results of each successful update operation, if any. + + * - ``UpsertedCount`` + - | 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. + +A ``ClientBulkWriteException`` object contains the following properties: + +.. list-table:: + :header-rows: 1 + :stub-columns: 1 + + * - Property + - Description + * - ``connectionId`` + - | The connection identifier. + | + | **Data Type:** `ConnectionId <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Core.Connections.ConnectionId.html>`__ + * - ``message`` + - | The error message. + | + | **Data Type:** string + * - ``writeErrors`` + - | A dictionary of errors that occurred during the bulk write operation. + | + | **Data Type:** IReadOnlyDictionary`__> + * - ``partialResult`` + - | The results of any successful operations performed before the exception was thrown. + | + | **Data Type:** `ClientBulkWriteResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ClientBulkWriteResult.html>`__ + * - ``writeConcernErrors`` + - | Write concern errors that occurred during execution of the bulk write operation. + | + | **Data Type:** IReadOnlyList<`MongoWriteConcernException <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.MongoWriteConcernException.html>`__> + * - ``innerException`` + - | The inner exception. + | + | **Data Type:** `Exception `__ + +Additional Information +---------------------- + +To learn how to perform individual write operations, see the following guides: + +- :ref:`csharp-change-guide` +- :ref:`csharp-insert-guide` +- :ref:`csharp-delete-guide` + +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>`__ diff --git a/source/includes/fundamentals/code-examples/BulkWrite.cs b/source/includes/fundamentals/code-examples/BulkWrite.cs new file mode 100644 index 00000000..4ee5e0c6 --- /dev/null +++ b/source/includes/fundamentals/code-examples/BulkWrite.cs @@ -0,0 +1,201 @@ +using System; + +class BulkWrite +{ + static void InsertOne() + { + // start-bulk-insert-one + var insertOneModel = new BulkWriteInsertOneModel( + "sample_restaurants.restaurants", + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } + ); + // end-bulk-insert-one + } + + static void UpdateOne() + { + // start-bulk-update-one + var updateOneModel = new BulkWriteUpdateOneModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") + ); + // end-bulk-update-one + } + + 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") + ); + // end-bulk-update-many + } + + static void ReplaceOne() + { + // start-bulk-replace-one + var replaceOneModel = new BulkWriteReplaceOneModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("restaurant_id", "1234"), + new BsonDocument{ + { "name", "Mongo's Pizza" }, + { "cuisine", "Pizza" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } + ); + // end-bulk-replace-one + } + + static void DeleteOne() + { + // start-bulk-delete-one + var deleteOneModel = new BulkWriteDeleteOneModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("restaurant_id", "5678") + ); + // end-bulk-delete-one + } + + static void DeleteMany() + { + // start-bulk-delete-many + var deleteManyModel = new BulkWriteDeleteManyModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("name", "Mongo's Deli") + ); + // end-bulk-delete-many + } + + static void BulkWriteSync() + { + // start-bulk-write-sync + var client = new MongoClient("mongodb://localhost:27017"); + var collection = "sample_restaurants.restaurants"; + + var bulkWriteModels = new[] + { + new BulkWriteInsertOneModel( + collection, + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } + ), + new BulkWriteInsertOneModel( + collection, + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } + ), + new BulkWriteUpdateManyModel( + collection, + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") + ), + new BulkWriteDeleteOneModel( + collection, + Builders.Filter.Eq("restaurant_id", "1234") + ) + }; + + var results = client.BulkWrite(bulkWriteModels); + Console.WriteLine("Bulk write results: " + results); + // 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 bulkWriteModels = new[] + { + new BulkWriteInsertOneModel( + collection, + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Manhattan" }, + { "restaurant_id", "1234" } + } + ), + new BulkWriteInsertOneModel( + collection, + new BsonDocument{ + { "name", "Mongo's Deli" }, + { "cuisine", "Sandwiches" }, + { "borough", "Brooklyn" }, + { "restaurant_id", "5678" } + } + ), + new BulkWriteUpdateManyModel( + collection, + Builders.Filter.Eq("name", "Mongo's Deli"), + Builders.Update.Set("cuisine", "Sandwiches and Salads") + ), + new BulkWriteDeleteOneModel( + collection, + Builders.Filter.Eq("restaurant_id", "1234") + ) + }; + + var results = await client.BulkWriteAsync(bulkWriteModels); + Console.WriteLine("Bulk write results: " + results); + // end-bulk-write-async + } + + static void BulkWriteOptionsSync() + { + // start-bulk-write-options-sync + var client = new MongoClient("mongodb://localhost:27017"); + + var deleteOneModel = new BulkWriteDeleteOneModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("restaurant_id", "5678") + ); + + var clientBulkWriteOptions = new ClientBulkWriteOptions + { + IsOrdered = false, + WriteConcern = WriteConcern.Unacknowledged, + VerboseResult = true + }; + + var results = client.BulkWrite(deleteOneModel, clientBulkWriteOptions); + // end-bulk-write-options-sync + } + static async Task BulkWriteOptionsAsync() + { + // start-bulk-write-options-async + var client = new MongoClient("mongodb://localhost:27017"); + + var deleteOneModel = new BulkWriteDeleteOneModel( + "sample_restaurants.restaurants", + Builders.Filter.Eq("restaurant_id", "5678") + ); + + var clientBulkWriteOptions = new ClientBulkWriteOptions + { + IsOrdered = false, + WriteConcern = WriteConcern.Unacknowledged, + VerboseResult = true + }; + + var results = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions); + // end-bulk-write-options-async + } +} \ No newline at end of file diff --git a/source/whats-new.txt b/source/whats-new.txt index d23b430a..c66dad0f 100644 --- a/source/whats-new.txt +++ b/source/whats-new.txt @@ -148,6 +148,9 @@ The 3.0 driver release includes the following new features: To learn more about using the aggregation pipeline with the {+driver-short+}, see :ref:`csharp-aggregation`. +- Adds a ``MongoClient`` API for bulk write operations. To learn more about bulk write + operations, see :ref:`csharp-bulk-write`. + For more information about this release, see the :github:`v3.0 release notes `.