Skip to content

Commit 9b236ca

Browse files
committed
replace page
1 parent 8bf2f9e commit 9b236ca

File tree

3 files changed

+218
-142
lines changed

3 files changed

+218
-142
lines changed

source/fundamentals/crud/write-operations/replace.txt

Lines changed: 147 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -24,81 +24,106 @@ Overview
2424
In this guide, you can learn how to use the {+driver-long+} to replace
2525
documents in a MongoDB collection.
2626

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.
2731

32+
Sample Data
33+
~~~~~~~~~~~
2834

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>`.
3139

32-
- ``ReplaceOneAsync()`` or ``ReplaceOne()``
40+
.. include:: /includes/convention-pack-note.rst
3341

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+
---------------
3844

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:
4147

42-
The ``ReplaceOne()`` method requires the following parameters:
48+
.. list-table::
49+
:widths: 30 70
50+
:header-rows: 1
4351

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
4854

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.
5458

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>``
6060

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.
6265

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``
6567

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``.
6871

69-
.. tabs::
72+
**Data Type:** `ReplaceOptions <{+new-api-root+>/MongoDB.Driver/MongoDB.Driver.ReplaceOptions.html>`__
7073

71-
.. tab:: Asynchronous
72-
:tabid: replace-one-async
74+
* - ``cancellationToken``
75+
- *Optional.* A token that you can use to cancel the operation.
7376

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.
7687

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::
7892

7993
.. tab:: Synchronous
8094
:tabid: replace-one-sync
8195

82-
.. code-block:: csharp
96+
.. literalinclude:: /includes/code-examples/replace-one/ReplaceOne.cs
97+
:language: csharp
8398
: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
84105

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
86112

87-
.. tip::
113+
.. important::
88114

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.
91117

92118
Customize the Replace Operation
93119
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94120

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
96123
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.
99125

100-
The ``ReplaceOptions`` type allows you to configure options with the
101-
following properties:
126+
The ``ReplaceOptions`` class contains the following properties:
102127

103128
.. list-table::
104129
:widths: 30 70
@@ -108,42 +133,82 @@ following properties:
108133
- Description
109134

110135
* - ``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?``
115142

116143
* - ``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>`__
120149

121150
* - ``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>`__
125156

126157
* - ``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>`__
130163

131164
* - ``IsUpsert``
132165
- | Specifies whether the replace operation performs an upsert operation if no
133166
documents match the query filter.
134167
See :manual:`the MongoDB server manual </reference/command/update/#std-label-update-command-upsert>`
135168
for more information.
136169

170+
**Data Type:** ``bool``
171+
137172
* - ``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
141205

142206
Return Value
143207
~~~~~~~~~~~~
144208

145209
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:
147212

148213
.. list-table::
149214
:widths: 30 70
@@ -153,77 +218,38 @@ object. The ``ReplaceOneResult`` type contains the following properties:
153218
- Description
154219

155220
* - ``IsAcknowledged``
156-
- | Indicates whether the replace operation was acknowledged by MongoDB.
221+
- Indicates whether the replace operation was acknowledged by MongoDB.
157222

223+
**Data Type:** ``bool``
224+
158225
* - ``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``
161230

162231
* - ``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``
165236

166237
* - ``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``
168241

169242
* - ``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>`__
221247

222248
API Documentation
223249
~~~~~~~~~~~~~~~~~
224250

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:
227253

228254
* `ReplaceOne() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOne.html>`__
229255
* `ReplaceOneAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.ReplaceOneAsync.html>`__

0 commit comments

Comments
 (0)