Skip to content

Commit fa491a9

Browse files
authored
DOCSP-26545 Fundamentals > ReplaceOne (#47)
* add replace method * replaceOne changes * fixes * fixes * fixes * fixes * fixes * fixes * dd feedback * db feedback
1 parent db4c9c4 commit fa491a9

File tree

6 files changed

+303
-24
lines changed

6 files changed

+303
-24
lines changed

source/fundamentals/crud/write-operations.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,5 @@ Write Operations
1212
:caption: Write Operations
1313

1414
/fundamentals/crud/write-operations/insert
15-
/fundamentals/crud/write-operations/update
15+
/fundamentals/crud/write-operations/change
1616
/fundamentals/crud/write-operations/delete

source/fundamentals/crud/write-operations/update.txt renamed to source/fundamentals/crud/write-operations/change.txt

Lines changed: 219 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
.. _csharp-update-guide:
1+
.. _csharp-change-guide:
22

33
================
4-
Update Documents
4+
Change Documents
55
================
66

77
.. default-domain:: mongodb
@@ -15,8 +15,11 @@ Update Documents
1515
Overview
1616
--------
1717

18-
In this guide, you'll learn how to edit existing documents or upsert new documents
19-
in your MongoDB collections using update operations.
18+
In this guide, you can learn how to change documents in a MongoDB
19+
collection using two different kinds of operations:
20+
21+
- :ref:`Update <csharp-update-operation>`
22+
- :ref:`Replace <csharp-replace-operation>`
2023

2124
Sample Data
2225
~~~~~~~~~~~
@@ -25,7 +28,7 @@ The examples in this guide use the ``restaurants`` collection
2528
from the ``sample_restaurants`` database. The documents in this
2629
collection use the following ``Restaurant`` class as a model:
2730

28-
.. literalinclude:: /includes/fundamentals/code-examples/crud/update/Restaurant.cs
31+
.. literalinclude:: /includes/fundamentals/code-examples/crud/change/Restaurant.cs
2932
:language: csharp
3033
:dedent:
3134
:start-after: start-model
@@ -35,6 +38,8 @@ This collection is from the :atlas:`sample datasets </sample-data>` provided
3538
by Atlas. See the :ref:`<csharp-quickstart>` to learn how to create a free MongoDB cluster
3639
and load this sample data.
3740

41+
.. _csharp-update-operation:
42+
3843
Update Operations
3944
-----------------
4045

@@ -59,11 +64,12 @@ Each update method requires the following parameters:
5964
The {+driver-short+} provides a ``Builders`` class that simplifies the creation of both
6065
query filters and update documents. The following code sample uses ``Builders`` to create
6166
two documents for use as parameters in an update operation:
67+
6268
- A query filter that searches for restaurants with a ``borough`` field value of "Manhattan"
6369
- An update document that sets the value of the ``borough`` field of these restaurants
64-
to "Manhattan (north)"
70+
to "Manhattan (north)"
6571

66-
.. literalinclude:: /includes/fundamentals/code-examples/crud/update/Update.cs
72+
.. literalinclude:: /includes/fundamentals/code-examples/crud/change/Update.cs
6773
:language: csharp
6874
:dedent:
6975
:start-after: start-builders
@@ -129,13 +135,13 @@ update all matched documents.
129135
.. tip::
130136

131137
Find runnable examples that use these methods under :ref:`Additional
132-
Information <csharp-update-info>`.
138+
Information <csharp-change-info>`.
133139

134140
Customize the Update Operation
135141
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136142

137-
Both methods optionally take an ``UpdateOptions`` type as an additional parameter,
138-
which represents options you can use to configure the delete operation.
143+
Both methods optionally accept an ``UpdateOptions`` object as an additional parameter,
144+
which represents options you can use to configure the update operation.
139145
If you don't specify any ``UpdateOptions`` properties, the driver does
140146
not customize the update operation.
141147

@@ -183,7 +189,7 @@ following properties:
183189

184190
* - ``Let``
185191
- | Gets or sets the let document.
186-
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-command-upsert>`
192+
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-let-syntax>`
187193
for more information.
188194

189195
Return Value
@@ -265,33 +271,226 @@ match any existing documents.
265271
``UpdateMany()``, the driver would update only the first of the
266272
matched documents.
267273

268-
.. _csharp-update-info:
274+
.. _csharp-replace-operation:
275+
276+
Replace Operation
277+
-----------------
278+
279+
You can perform a replace operation in MongoDB with the ``ReplaceOne()`` method.
280+
This method removes all fields (except the ``_id`` field) from the first document that
281+
matches the search criteria, then inserts the fields and values you specify into the
282+
document.
283+
284+
Required Parameters
285+
~~~~~~~~~~~~~~~~~~~
286+
287+
The ``ReplaceOne()`` method requires the following parameters:
288+
289+
- A query filter document, which determines which record to replace.
290+
- A **replacement** document, which specifies the fields and values to insert in the new
291+
document. If the documents in your collection are mapped to a {+language+} class,
292+
the replacement document can be an instance of this class.
293+
294+
Like in an update operation, you can use the ``Builders`` class in the {+driver-short+}
295+
to create a query filter.
296+
The following code sample uses ``Builders`` to create a query filter that searches
297+
for restaurants with a ``name`` field value of "Pizza Town". The code also creates a new
298+
``Restaurant`` object that will replace the first matched document.
299+
300+
.. literalinclude:: /includes/fundamentals/code-examples/crud/change/Replace.cs
301+
:language: csharp
302+
:dedent:
303+
:start-after: // start-parameters
304+
:end-before: // end-parameters
305+
306+
.. important::
307+
308+
The values of ``_id`` fields are immutable. If your replacement document specifies
309+
a value for the ``_id`` field, it must match the ``_id`` value of the existing document.
310+
311+
The following code shows how to use the asynchronous ``ReplaceOneAsync()`` method
312+
or the synchronous ``ReplaceOne()`` method to replace one document.
313+
314+
.. tabs::
315+
316+
.. tab:: Asynchronous
317+
:tabid: replace-one-async
318+
319+
.. code-block:: csharp
320+
:copyable: true
321+
322+
var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant);
323+
324+
.. tab:: Synchronous
325+
:tabid: replace-one-sync
326+
327+
.. code-block:: csharp
328+
:copyable: true
329+
330+
var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant);
331+
332+
.. tip::
333+
334+
Find runnable examples that use these methods under :ref:`Additional
335+
Information <csharp-change-info>`.
336+
337+
Customize the Replace Operation
338+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
339+
340+
The ``ReplaceOne()`` method optionally accepts a ``ReplaceOptions`` object as an
341+
additional parameter, which represents options you can use to configure the replace
342+
operation. If you don't specify any ``ReplaceOptions`` properties, the driver does
343+
not customize the replace operation.
344+
345+
The ``ReplaceOptions`` type allows you to configure options with the
346+
following properties:
347+
348+
.. list-table::
349+
:widths: 30 70
350+
:header-rows: 1
351+
352+
* - Property
353+
- Description
354+
355+
* - ``BypassDocumentValidation``
356+
- | Specifies whether the replace operation bypasses document validation. This lets you
357+
replace documents that don't meet the schema validation requirements, if any
358+
exist. See :manual:`the MongoDB server manual</core/schema-validation/#schema-validation>`
359+
for more information on schema validation.
360+
361+
* - ``Collation``
362+
- | Specifies the kind of language collation to use when sorting
363+
results. See :manual:`the MongoDB server manual</reference/collation/#std-label-collation>`
364+
for more information on collation.
365+
366+
* - ``Comment``
367+
- | Gets or sets the user-provided comment for the operation.
368+
See :manual:`the MongoDB server manual</reference/command/update/#command-fields>`
369+
for more information.
370+
371+
* - ``Hint``
372+
- | Gets or sets the index to use to scan for documents.
373+
See :manual:`the MongoDB server manual</reference/command/update/#std-label-update-command-hint>`
374+
for more information.
375+
376+
* - ``IsUpsert``
377+
- | Specifies whether the replace operation performs an upsert operation if no
378+
documents match the query filter.
379+
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-command-upsert>`
380+
for more information.
381+
382+
* - ``Let``
383+
- | Gets or sets the let document.
384+
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-let-syntax>`
385+
for more information.
386+
387+
Return Value
388+
~~~~~~~~~~~~
389+
390+
The ``ReplaceOne()`` method returns a ``ReplaceOneResult``
391+
object. The ``ReplaceOneResult`` type contains the following properties:
392+
393+
.. list-table::
394+
:widths: 30 70
395+
:header-rows: 1
396+
397+
* - Property
398+
- Description
399+
400+
* - ``IsAcknowledged``
401+
- | Indicates whether the replace operation was acknowledged by MongoDB.
402+
403+
* - ``IsModifiedCountAvailable``
404+
- | Indicates whether you can read the count of replaced records on the
405+
``ReplaceOneResult``.
406+
407+
* - ``MatchedCount``
408+
- | The number of documents that matched the query filter, regardless of
409+
whether one was replaced.
410+
411+
* - ``ModifiedCount``
412+
- | The number of documents replaced by the replace operation.
413+
414+
* - ``UpsertedId``
415+
- | The ID of the document that was upserted in the database, if the driver
416+
performed an upsert.
417+
418+
Example
419+
~~~~~~~
420+
421+
The following code uses the ``ReplaceOne()`` method to find the first document where the
422+
``name`` field has the value "Pizza Town", then replaces this document
423+
with a new ``Restaurant`` document named "Food World". Because the ``IsUpsert`` option is
424+
set to ``true``, the driver inserts a new document if the query filter doesn't
425+
match any existing documents.
426+
427+
.. io-code-block::
428+
:copyable: true
429+
430+
.. input::
431+
:language: csharp
432+
433+
var filter = Builders<Restaurant>.Filter.Eq(restaurant => restaurant.Name, "Pizza Town");
434+
435+
Restaurant newRestaurant = new()
436+
{
437+
Name = "Food World",
438+
Cuisine = "American",
439+
Address = new BsonDocument
440+
{
441+
{"street", "Food St"},
442+
{"zipcode", "10003"},
443+
},
444+
Borough = "Manhattan",
445+
};
446+
447+
ReplaceOptions opts = new ReplaceOptions()
448+
{
449+
Comment = new BsonString("Restaurant replaced for {+driver-short+} Fundamentals"),
450+
IsUpsert = true
451+
};
452+
453+
WriteLine("Replacing document...");
454+
var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts);
455+
456+
WriteLine($"Replaced documents: {result.ModifiedCount}");
457+
WriteLine($"Result acknowledged? {result.IsAcknowledged}");
458+
459+
.. output::
460+
:language: none
461+
:visible: false
462+
463+
Replacing document...
464+
Replaced documents: 1
465+
Result acknowledged? True
466+
467+
.. _csharp-change-info:
269468

270469
Additional Information
271470
----------------------
272471

273-
For runnable examples of the delete operations, see the following usage
472+
For runnable examples of the update and replace operations, see the following usage
274473
examples:
275474

276475
- :ref:`csharp-update-one`
277476
- :ref:`csharp-update-many`
477+
- :ref:`csharp-replace-one`
278478

279-
.. To learn more about performing the operations mentioned, see the
280-
.. following guides:
281-
282-
.. TODO create specify a query
283-
.. - :ref:`csharp-query-document`
479+
To learn more about creating query filters, see the :ref:`csharp-specify-query` guide.
284480

285481
API Documentation
286482
~~~~~~~~~~~~~~~~~
287483

288484
To learn more about any of the methods or types discussed in this
289-
guide, see the following API Documentation:
485+
guide, see the following API documentation:
290486

291487
* `UpdateOne() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateOne.htm>`__
292488
* `UpdateOneAsync() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateOneAsync.htm>`__
293489
* `UpdateMany() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateMany.htm>`__
294490
* `UpdateManyAsync() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_UpdateManyAsync.htm>`__
295491
* `UpdateOptions <{+api-root+}/T_MongoDB_Driver_UpdateOptions.htm>`__
296492
* `UpdateResult <{+api-root+}/T_MongoDB_Driver_UpdateResult.htm>`__
297-
493+
* `ReplaceOne() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_ReplaceOne.htm>`__
494+
* `ReplaceOneAsync() <{+api-root+}/M_MongoDB_Driver_IMongoCollection_1_ReplaceOneAsync.htm>`__
495+
* `ReplaceOptions <{+api-root+}/T_MongoDB_Driver_ReplaceOptions.htm>`__
496+
* `ReplaceOneResult <{+api-root+}/T_MongoDB_Driver_ReplaceOneResult.htm>`__

0 commit comments

Comments
 (0)