|
| 1 | +.. _csharp-replace-operation: |
| 2 | +.. _csharp-replace-documents: |
| 3 | + |
| 4 | +================= |
| 5 | +Replace Documents |
| 6 | +================= |
| 7 | + |
| 8 | +.. contents:: On this page |
| 9 | + :local: |
| 10 | + :backlinks: none |
| 11 | + :depth: 2 |
| 12 | + :class: singlecol |
| 13 | + |
| 14 | +.. facet:: |
| 15 | + :name: genre |
| 16 | + :values: reference |
| 17 | + |
| 18 | +.. meta:: |
| 19 | + :keywords: replace, synchronous, asynchronous |
| 20 | + |
| 21 | +Overview |
| 22 | +-------- |
| 23 | + |
| 24 | +In this guide, you can learn how to use the {+driver-long+} to replace |
| 25 | +documents in a MongoDB collection. |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +The {+driver-short+} provides the following methods to modify documents, |
| 30 | +each of which has an asynchronous and synchronous version: |
| 31 | + |
| 32 | +- ``ReplaceOneAsync()`` or ``ReplaceOne()`` |
| 33 | + |
| 34 | +You can perform a replace operation in MongoDB with the ``ReplaceOne()`` method. |
| 35 | +This method removes all fields (except the ``_id`` field) from the first document that |
| 36 | +matches the search criteria, then inserts the fields and values you specify into the |
| 37 | +document. |
| 38 | + |
| 39 | +Required Parameters |
| 40 | +~~~~~~~~~~~~~~~~~~~ |
| 41 | + |
| 42 | +The ``ReplaceOne()`` method requires the following parameters: |
| 43 | + |
| 44 | +- A query filter document, which determines which record to replace. |
| 45 | +- A **replacement** document, which specifies the fields and values to insert in the new |
| 46 | + document. If the documents in your collection are mapped to a {+language+} class, |
| 47 | + the replacement document can be an instance of this class. |
| 48 | + |
| 49 | +Like in an update operation, you can use the ``Builders`` class in the {+driver-short+} |
| 50 | +to create a query filter. |
| 51 | +The following code sample uses ``Builders`` to create a query filter that searches |
| 52 | +for restaurants with a ``name`` field value of "Pizza Town". The code also creates a new |
| 53 | +``Restaurant`` object that will replace the first matched document. |
| 54 | + |
| 55 | +.. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs |
| 56 | + :language: csharp |
| 57 | + :dedent: |
| 58 | + :start-after: // start-replace-one |
| 59 | + :end-before: // end-replace-one |
| 60 | + |
| 61 | +.. important:: |
| 62 | + |
| 63 | + The values of ``_id`` fields are immutable. If your replacement document specifies |
| 64 | + a value for the ``_id`` field, it must match the ``_id`` value of the existing document. |
| 65 | + |
| 66 | +The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method |
| 67 | +or the synchronous ``ReplaceOne()`` method to replace one document. |
| 68 | + |
| 69 | +.. tabs:: |
| 70 | + |
| 71 | + .. tab:: Asynchronous |
| 72 | + :tabid: replace-one-async |
| 73 | + |
| 74 | + .. code-block:: csharp |
| 75 | + :copyable: true |
| 76 | + |
| 77 | + var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant); |
| 78 | + |
| 79 | + .. tab:: Synchronous |
| 80 | + :tabid: replace-one-sync |
| 81 | + |
| 82 | + .. code-block:: csharp |
| 83 | + :copyable: true |
| 84 | + |
| 85 | + var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant); |
| 86 | + |
| 87 | +.. tip:: |
| 88 | + |
| 89 | + Find runnable examples that use these methods under :ref:`Additional |
| 90 | + Information <csharp-change-info>`. |
| 91 | + |
| 92 | +Customize the Replace Operation |
| 93 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 94 | + |
| 95 | +The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an |
| 96 | +additional parameter, which represents options you can use to configure the replace |
| 97 | +operation. If you don't specify any ``ReplaceOptions`` properties, the driver does |
| 98 | +not customize the replace operation. |
| 99 | + |
| 100 | +The ``ReplaceOptions`` type allows you to configure options with the |
| 101 | +following properties: |
| 102 | + |
| 103 | +.. list-table:: |
| 104 | + :widths: 30 70 |
| 105 | + :header-rows: 1 |
| 106 | + |
| 107 | + * - Property |
| 108 | + - Description |
| 109 | + |
| 110 | + * - ``BypassDocumentValidation`` |
| 111 | + - | Specifies whether the replace operation bypasses document validation. This lets you |
| 112 | + replace documents that don't meet the schema validation requirements, if any |
| 113 | + exist. See :manual:`the MongoDB server manual</core/schema-validation/#schema-validation>` |
| 114 | + for more information on schema validation. |
| 115 | + |
| 116 | + * - ``Collation`` |
| 117 | + - | Specifies the kind of language collation to use when sorting |
| 118 | + results. See :manual:`the MongoDB server manual</reference/collation/#std-label-collation>` |
| 119 | + for more information on collation. |
| 120 | + |
| 121 | + * - ``Comment`` |
| 122 | + - | Gets or sets the user-provided comment for the operation. |
| 123 | + See :manual:`the MongoDB server manual</reference/command/update/#command-fields>` |
| 124 | + for more information. |
| 125 | + |
| 126 | + * - ``Hint`` |
| 127 | + - | Gets or sets the index to use to scan for documents. |
| 128 | + See :manual:`the MongoDB server manual</reference/command/update/#std-label-update-command-hint>` |
| 129 | + for more information. |
| 130 | + |
| 131 | + * - ``IsUpsert`` |
| 132 | + - | Specifies whether the replace operation performs an upsert operation if no |
| 133 | + documents match the query filter. |
| 134 | + See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-command-upsert>` |
| 135 | + for more information. |
| 136 | + |
| 137 | + * - ``Let`` |
| 138 | + - | Gets or sets the let document. |
| 139 | + See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-let-syntax>` |
| 140 | + for more information. |
| 141 | + |
| 142 | +Return Value |
| 143 | +~~~~~~~~~~~~ |
| 144 | + |
| 145 | +The ``ReplaceOne()`` method returns a ``ReplaceOneResult`` |
| 146 | +object. The ``ReplaceOneResult`` type contains the following properties: |
| 147 | + |
| 148 | +.. list-table:: |
| 149 | + :widths: 30 70 |
| 150 | + :header-rows: 1 |
| 151 | + |
| 152 | + * - Property |
| 153 | + - Description |
| 154 | + |
| 155 | + * - ``IsAcknowledged`` |
| 156 | + - | Indicates whether the replace operation was acknowledged by MongoDB. |
| 157 | + |
| 158 | + * - ``IsModifiedCountAvailable`` |
| 159 | + - | Indicates whether you can read the count of replaced records on the |
| 160 | + ``ReplaceOneResult``. |
| 161 | + |
| 162 | + * - ``MatchedCount`` |
| 163 | + - | The number of documents that matched the query filter, regardless of |
| 164 | + whether one was replaced. |
| 165 | + |
| 166 | + * - ``ModifiedCount`` |
| 167 | + - | The number of documents replaced by the replace operation. |
| 168 | + |
| 169 | + * - ``UpsertedId`` |
| 170 | + - | The ID of the document that was upserted in the database, if the driver |
| 171 | + performed an upsert. |
| 172 | + |
| 173 | +Example |
| 174 | +~~~~~~~ |
| 175 | + |
| 176 | +The following code uses the ``ReplaceOne()`` method to find the first document where the |
| 177 | +``name`` field has the value "Pizza Town", then replaces this document |
| 178 | +with a new ``Restaurant`` document named "Food World". Because the ``IsUpsert`` option is |
| 179 | +set to ``true``, the driver inserts a new document if the query filter doesn't |
| 180 | +match any existing documents. |
| 181 | + |
| 182 | +.. io-code-block:: |
| 183 | + :copyable: true |
| 184 | + |
| 185 | + .. input:: |
| 186 | + :language: csharp |
| 187 | + |
| 188 | + var filter = Builders<Restaurant>.Filter.Eq(restaurant => restaurant.Name, "Pizza Town"); |
| 189 | + |
| 190 | + Restaurant newRestaurant = new() |
| 191 | + { |
| 192 | + Name = "Food World", |
| 193 | + Cuisine = "American", |
| 194 | + Address = new BsonDocument |
| 195 | + { |
| 196 | + {"street", "Food St"}, |
| 197 | + {"zipcode", "10003"}, |
| 198 | + }, |
| 199 | + Borough = "Manhattan", |
| 200 | + }; |
| 201 | + |
| 202 | + ReplaceOptions opts = new ReplaceOptions() |
| 203 | + { |
| 204 | + Comment = new BsonString("Restaurant replaced for {+driver-short+} Fundamentals"), |
| 205 | + IsUpsert = true |
| 206 | + }; |
| 207 | + |
| 208 | + Console.WriteLine("Replacing document..."); |
| 209 | + var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts); |
| 210 | + |
| 211 | + Console.WriteLine($"Replaced documents: {result.ModifiedCount}"); |
| 212 | + Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}"); |
| 213 | + |
| 214 | + .. output:: |
| 215 | + :language: none |
| 216 | + :visible: false |
| 217 | + |
| 218 | + Replacing document... |
| 219 | + Replaced documents: 1 |
| 220 | + Result acknowledged? True |
| 221 | + |
| 222 | +API Documentation |
| 223 | +~~~~~~~~~~~~~~~~~ |
| 224 | + |
| 225 | +To learn more about any of the methods or types discussed in this |
| 226 | +guide, see the following API documentation: |
| 227 | + |
| 228 | +* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__ |
| 229 | +* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__ |
| 230 | +* `ReplaceOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__ |
| 231 | +* `ReplaceOneResult <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ReplaceOneResult.html>`__ |
0 commit comments