@@ -24,81 +24,106 @@ Overview
24
24
In this guide, you can learn how to use the {+driver-long+} to replace
25
25
documents in a MongoDB collection.
26
26
27
+ The {+driver-short+} provides the ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods.
28
+ These methods remove all fields (except the ``_id`` field) from the first document that
29
+ matches the search criteria, then insert the fields and values you specify into the
30
+ document.
27
31
32
+ Sample Data
33
+ ~~~~~~~~~~~
28
34
29
- The {+driver-short+} provides the following methods to modify documents,
30
- each of which has an asynchronous and synchronous version:
35
+ The examples in this guide use the ``restaurants`` collection
36
+ in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets </sample-data>`.
37
+ To learn how to create a free MongoDB Atlas cluster and load the sample datasets,
38
+ see the :ref:`<csharp-quickstart>`.
31
39
32
- - ``ReplaceOneAsync()`` or ``ReplaceOne()``
40
+ .. include:: /includes/convention-pack-note.rst
33
41
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.
42
+ Replace Methods
43
+ ---------------
38
44
39
- Required Parameters
40
- ~~~~~~~~~~~~~~~~~~~
45
+ To replace a document in a collection, call the ``ReplaceOne()`` or ``ReplaceOneAsync()``
46
+ method. These methods accept the following parameters:
41
47
42
- The ``ReplaceOne()`` method requires the following parameters:
48
+ .. list-table::
49
+ :widths: 30 70
50
+ :header-rows: 1
43
51
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.
52
+ * - Parameter
53
+ - Description
48
54
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.
55
+ * - ``filter``
56
+ - A *query filter* document that specifies the record to replace. You can use the
57
+ ``Builders`` class to create a query filter.
54
58
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
59
+ **Data Type:** `FilterDefinition <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.FilterDefinition-1.html>`__ ``<TDocument>``
60
60
61
- .. important::
61
+ * - ``replacement``
62
+ - A *replacement* document, which specifies the fields and values to insert in the new
63
+ document. If the documents in your collection are mapped to a {+language+} class,
64
+ the replacement document can be an instance of this class.
62
65
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.
66
+ **Data Type:** ``TDocument``
65
67
66
- The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method
67
- or the synchronous ``ReplaceOne()`` method to replace one document.
68
+ * - ``options``
69
+ - *Optional.* An instance of the ``ReplaceOptions`` class that specifies the
70
+ configuration for the replace operation. The default value is ``null``.
68
71
69
- .. tabs::
72
+ **Data Type:** `ReplaceOptions <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__
70
73
71
- .. tab:: Asynchronous
72
- :tabid: replace-one-async
74
+ * - ``cancellationToken``
75
+ - *Optional.* A token that you can use to cancel the operation.
73
76
74
- .. code-block:: csharp
75
- :copyable: true
77
+ **Data type**: `CancellationToken <https://learn.microsoft.com/dotnet/api/system.threading.cancellationtoken>`__
78
+
79
+ The following code example performs the following steps:
80
+
81
+ 1. Uses the ``Builders`` class to create a query filter. The filter matches all
82
+ documents where the ``cuisine`` field has the value ``"Pizza"``.
83
+ #. Creates a new ``Restaurant`` object.
84
+ #. Calls the ``ReplaceOne()`` method on the ``restaurants`` collection. This operation
85
+ find the first matching document in the collection and replaces it with the newly created
86
+ document.
76
87
77
- var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant);
88
+ Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the
89
+ corresponding code.
90
+
91
+ .. tabs::
78
92
79
93
.. tab:: Synchronous
80
94
:tabid: replace-one-sync
81
95
82
- .. code-block:: csharp
96
+ .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs
97
+ :language: csharp
83
98
:copyable: true
99
+ :dedent:
100
+ :start-after: // start-replace-one-sync
101
+ :end-before: // end-replace-one-sync
102
+
103
+ .. tab:: Asynchronous
104
+ :tabid: replace-one-async
84
105
85
- var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant);
106
+ .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs
107
+ :language: csharp
108
+ :copyable: true
109
+ :dedent:
110
+ :start-after: // start-replace-one-async
111
+ :end-before: // end-replace-one-async
86
112
87
- .. tip ::
113
+ .. important ::
88
114
89
- Find runnable examples that use these methods under :ref:`Additional
90
- Information <csharp-change-info>` .
115
+ The values of ``_id`` fields are immutable. If your replacement document specifies
116
+ a value for the ``_id`` field, it must match the ``_id`` value of the existing document .
91
117
92
118
Customize the Replace Operation
93
119
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94
120
95
- The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an
121
+ The ``ReplaceOne()`` and ``ReplaceOneAsync()`` methods optionally accept a
122
+ ``ReplaceOptions`` object as an
96
123
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.
124
+ operation.
99
125
100
- The ``ReplaceOptions`` type allows you to configure options with the
101
- following properties:
126
+ The ``ReplaceOptions`` class contains the following properties:
102
127
103
128
.. list-table::
104
129
:widths: 30 70
@@ -108,42 +133,82 @@ following properties:
108
133
- Description
109
134
110
135
* - ``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.
136
+ - Specifies whether the replace operation bypasses document validation. This lets you
137
+ replace documents that don't meet the schema validation requirements, if any
138
+ exist. See :manual:`the MongoDB server manual</core/schema-validation/#schema-validation>`
139
+ for more information on schema validation.
140
+
141
+ **Data Type:** ``bool?``
115
142
116
143
* - ``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.
144
+ - Specifies the kind of language collation to use when sorting
145
+ results. See :manual:`the MongoDB server manual</reference/collation/#std-label-collation>`
146
+ for more information on collation.
147
+
148
+ **Data Type:** `Collation <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Collation.html>`__
120
149
121
150
* - ``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.
151
+ - Gets or sets the user-provided comment for the operation.
152
+ See :manual:`the MongoDB server manual</reference/command/update/#command-fields>`
153
+ for more information.
154
+
155
+ **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__
125
156
126
157
* - ``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.
158
+ - Gets or sets the index to use to scan for documents.
159
+ See :manual:`the MongoDB server manual</reference/command/update/#std-label-update-command-hint>`
160
+ for more information.
161
+
162
+ **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__
130
163
131
164
* - ``IsUpsert``
132
165
- | Specifies whether the replace operation performs an upsert operation if no
133
166
documents match the query filter.
134
167
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-command-upsert>`
135
168
for more information.
136
169
170
+ **Data Type:** ``bool``
171
+
137
172
* - ``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.
173
+ - Gets or sets the let document.
174
+ See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-let-syntax>`
175
+ for more information.
176
+
177
+ **Data Type:** `BsonDocument <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonDocument.html>`__
178
+
179
+ The following example performs the same steps as the preceding example, but also uses
180
+ the ``BypassDocumentValidation`` option to bypass any schema validation requirements.
181
+ Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding
182
+ code.
183
+
184
+ .. tabs::
185
+
186
+ .. tab:: Synchronous
187
+ :tabid: replace-one-sync-with-options
188
+
189
+ .. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs
190
+ :language: csharp
191
+ :copyable: true
192
+ :dedent:
193
+ :start-after: // start-replace-one-sync-with-options
194
+ :end-before: // end-replace-one-sync-with-options
195
+
196
+ .. tab:: Asynchronous
197
+ :tabid: replace-one-async-with-options
198
+
199
+ .. literalinclude:: /includes/code-examples/replace-one/ReplaceOneAsync.cs
200
+ :language: csharp
201
+ :copyable: true
202
+ :dedent:
203
+ :start-after: // start-replace-one-async-with-options
204
+ :end-before: // end-replace-one-async-with-options
141
205
142
206
Return Value
143
207
~~~~~~~~~~~~
144
208
145
209
The ``ReplaceOne()`` method returns a ``ReplaceOneResult``
146
- object. The ``ReplaceOneResult`` type contains the following properties:
210
+ object, and the ``ReplaceOneAsync()`` method returns a ``Task<ReplaceOneResult>`` object.
211
+ The ``ReplaceOneResult`` class contains the following properties:
147
212
148
213
.. list-table::
149
214
:widths: 30 70
@@ -153,77 +218,38 @@ object. The ``ReplaceOneResult`` type contains the following properties:
153
218
- Description
154
219
155
220
* - ``IsAcknowledged``
156
- - | Indicates whether the replace operation was acknowledged by MongoDB.
221
+ - Indicates whether the replace operation was acknowledged by MongoDB.
157
222
223
+ **Data Type:** ``bool``
224
+
158
225
* - ``IsModifiedCountAvailable``
159
- - | Indicates whether you can read the count of replaced records on the
160
- ``ReplaceOneResult``.
226
+ - Indicates whether you can read the count of replaced records on the
227
+ ``ReplaceOneResult``.
228
+
229
+ **Data Type:** ``bool``
161
230
162
231
* - ``MatchedCount``
163
- - | The number of documents that matched the query filter, regardless of
164
- whether one was replaced.
232
+ - The number of documents that matched the query filter, regardless of
233
+ whether one was replaced.
234
+
235
+ **Data Type:** ``long``
165
236
166
237
* - ``ModifiedCount``
167
- - | The number of documents replaced by the replace operation.
238
+ - The number of documents replaced by the replace operation.
239
+
240
+ **Data Type:** ``long``
168
241
169
242
* - ``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
243
+ - The ID of the document that was upserted in the database, if the driver
244
+ performed an upsert.
245
+
246
+ **Data Type:** `BsonValue <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BsonValue.html>`__
221
247
222
248
API Documentation
223
249
~~~~~~~~~~~~~~~~~
224
250
225
- To learn more about any of the methods or types discussed in this
226
- guide, see the following API documentation:
251
+ To learn more about any of the methods and classes used on this page,
252
+ see the following API documentation:
227
253
228
254
* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__
229
255
* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__
0 commit comments