Skip to content

Commit ad61726

Browse files
authored
DOCSP-41819: replace document (#29)
* DOCSP-41819: replace document * AS PR fixes 1 * fix * remove unused import
1 parent de2efaf commit ad61726

File tree

4 files changed

+243
-7
lines changed

4 files changed

+243
-7
lines changed

source/includes/write/replace.kt

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import com.mongodb.client.model.Filters
2+
import com.mongodb.client.model.ReplaceOptions
3+
import com.mongodb.kotlin.client.MongoClient
4+
5+
// start-data-class
6+
data class Restaurant(
7+
val name: String,
8+
val borough: String,
9+
val cuisine: String,
10+
val owner: String?,
11+
)
12+
// end-data-class
13+
14+
fun main() {
15+
val uri = "<connection string>"
16+
17+
val mongoClient = MongoClient.create(uri)
18+
val database = mongoClient.getDatabase("sample_restaurants")
19+
val collection = database.getCollection<Restaurant>("restaurants")
20+
21+
// start-replace-one
22+
val filter = Filters.eq(Restaurant::name.name, "Primola Restaurant")
23+
val replacement = Restaurant(
24+
"Frutti Di Mare",
25+
"Queens",
26+
"Seafood",
27+
owner = "Sal Thomas"
28+
)
29+
val result = collection.replaceOne(filter, replacement)
30+
// end-replace-one
31+
32+
// start-replace-options
33+
val opts = ReplaceOptions().upsert(true)
34+
val result = collection.replaceOne(filter, replacement, opts)
35+
// end-replace-options
36+
37+
}
38+

source/write-operations.txt

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ Write Data to MongoDB
2424

2525
/write/insert
2626
/write/update
27+
/write/replace
2728
/write/delete
2829
/write/bulk-write
2930

3031
..
31-
/write/replace
3232
/write/gridfs
3333

3434
Overview
@@ -135,8 +135,8 @@ collection with a new document:
135135
:copyable:
136136
:dedent:
137137

138-
.. To learn more about the ``replace_one()`` method, see the
139-
.. :ref:`Replace Documents <kotlin-sync-write-replace>` guide.
138+
To learn more about the ``replaceOne()`` method, see the
139+
:ref:`Replace Documents <kotlin-sync-write-replace>` guide.
140140

141141
Delete One
142142
----------

source/write/replace.txt

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
.. _kotlin-sync-write-replace:
2+
3+
=================
4+
Replace Documents
5+
=================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: modify, change, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-short+} to perform a **replace
24+
operation** on a document in a MongoDB collection. A replace operation
25+
removes all fields and values from a specified document except the
26+
``_id`` field, and adds new fields and values that you specify. This
27+
operations differs from an update operation, which changes only
28+
specified fields in one or more documents.
29+
30+
To learn more about update operations, see the
31+
:ref:`kotlin-sync-write-update` guide.
32+
33+
Sample Data
34+
~~~~~~~~~~~
35+
36+
The examples in this guide use the ``sample_restaurants.restaurants`` collection
37+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
38+
free MongoDB Atlas cluster and load the sample datasets, see the
39+
:atlas:`Get Started with Atlas </getting-started>` guide.
40+
41+
The documents in this collection are modeled by the following {+language+} data class:
42+
43+
.. literalinclude:: /includes/write/replace.kt
44+
:start-after: start-data-class
45+
:end-before: end-data-class
46+
:language: kotlin
47+
:copyable:
48+
:dedent:
49+
50+
Replace Operation
51+
-----------------
52+
53+
You can perform a replace operation in MongoDB by using the
54+
``replaceOne()`` method. This method removes all fields except the
55+
``_id`` field from the first document that matches the query filter. It
56+
then adds the fields and values you specify to the empty document.
57+
58+
Required Parameters
59+
~~~~~~~~~~~~~~~~~~~
60+
61+
You must pass the following parameters to the ``replaceOne()`` method:
62+
63+
- **Query filter**, which matches which documents to update. To learn
64+
more about query filters, see the :ref:`kotlin-sync-specify-query`
65+
guide.
66+
67+
- **Replacement document**, which specifies the fields and values that
68+
you want to replace the existing fields and values with.
69+
70+
Replace One Document
71+
--------------------
72+
73+
The following example uses the ``replaceOne()`` method to replace the
74+
fields and values of a document in which the value of the ``name`` field
75+
value is ``"Primola Restaurant"``:
76+
77+
.. literalinclude:: /includes/write/replace.kt
78+
:start-after: start-replace-one
79+
:end-before: end-replace-one
80+
:language: kotlin
81+
:copyable:
82+
:dedent:
83+
84+
.. important::
85+
86+
The values of ``_id`` fields are immutable. If your replacement
87+
document specifies a value for the ``_id`` field, it must be the same
88+
as the ``_id`` value of the existing document or the driver raises a
89+
``WriteError``.
90+
91+
Customize the Replace Operation
92+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93+
94+
The ``replaceOne()`` method optionally accepts
95+
a parameter that sets options to configure the replace operation.
96+
If you don't specify any options, the driver performs the replace
97+
operation with default settings.
98+
99+
The following table describes the setter methods that you can use to
100+
configure an ``ReplaceOptions`` instance:
101+
102+
.. list-table::
103+
:widths: 30 70
104+
:header-rows: 1
105+
106+
* - Property
107+
- Description
108+
109+
* - ``upsert()``
110+
- | Specifies whether the replace operation performs an upsert operation if no
111+
documents match the query filter. For more information, see :manual:`upsert
112+
behavior </reference/method/db.collection.replaceOne/#upsert>`
113+
in the {+mdb-server+} manual.
114+
| Defaults to ``false``
115+
116+
* - ``bypassDocumentValidation()``
117+
- | Specifies whether the update operation bypasses document validation. This lets you
118+
update documents that don't meet the schema validation requirements, if any
119+
exist. For more information about schema validation, see :manual:`Schema
120+
Validation </core/schema-validation/#schema-validation>` in the MongoDB
121+
Server manual.
122+
| Defaults to ``false``.
123+
124+
* - ``collation()``
125+
- | Specifies the kind of language collation to use when sorting
126+
results. For more information, see :manual:`Collation </reference/collation/#std-label-collation>`
127+
in the {+mdb-server+} manual.
128+
129+
* - ``hint()``
130+
- | Sets the index to use when matching documents.
131+
For more information, see the :manual:`hint statement
132+
</reference/method/db.collection.replaceOne/#std-label-replace-one-hint>`
133+
in the {+mdb-server+} manual.
134+
135+
* - ``let()``
136+
- | Provides a map of parameter names and values to set top-level
137+
variables for the operation. Values must be constant or closed
138+
expressions that don't reference document fields.
139+
140+
* - ``comment()``
141+
- | Sets a comment to attach to the operation.
142+
143+
The following code sets the ``upsert`` option to ``true``, which instructs the
144+
driver to insert a new document that has the fields and values specified
145+
in the replacement document if the query filter doesn't match any
146+
existing documents:
147+
148+
.. literalinclude:: /includes/write/replace.kt
149+
:start-after: start-replace-options
150+
:end-before: end-replace-options
151+
:language: kotlin
152+
:copyable:
153+
:dedent:
154+
155+
Return Value
156+
~~~~~~~~~~~~
157+
158+
The ``replaceOne()`` method returns an ``UpdateResult``
159+
object. You can use the following methods to access information from
160+
an ``UpdateResult`` instance:
161+
162+
.. list-table::
163+
:widths: 30 70
164+
:header-rows: 1
165+
166+
* - Property
167+
- Description
168+
169+
* - ``getMatchedCount()``
170+
- | Returns the number of documents that matched the query filter, regardless of
171+
how many updates were performed.
172+
173+
* - ``getModifiedCount()``
174+
- | Returns the number of documents modified by the update operation. If an updated
175+
document is identical to the original, it is not included in this
176+
count.
177+
178+
* - ``wasAcknowledged()``
179+
- | Returns ``true`` if the server acknowledged the result.
180+
181+
* - ``getUpsertedId()``
182+
- | Returns the ``_id`` value of the document that was upserted
183+
in the database, if the driver performed an upsert.
184+
185+
Additional Information
186+
----------------------
187+
188+
To view a runnable code example that demonstrates how to replace a
189+
document, see :ref:`kotlin-sync-write`.
190+
191+
API Documentation
192+
~~~~~~~~~~~~~~~~~
193+
194+
To learn more about any of the methods or types discussed in this
195+
guide, see the following API documentation:
196+
197+
- `replaceOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/replace-one.html>`__
198+
- `UpdateResult <{+core-api+}/com/mongodb/client/result/UpdateResult.html>`__

source/write/update.txt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,19 +183,19 @@ an ``UpdateResult`` instance:
183183
- Description
184184

185185
* - ``getMatchedCount()``
186-
- | Indicates the number of documents that matched the query filter, regardless of
186+
- | Returns the number of documents that matched the query filter, regardless of
187187
how many updates were performed.
188188

189189
* - ``getModifiedCount()``
190-
- | Indicates number of documents modified by the update operation. If an updated
190+
- | Returns the number of documents modified by the update operation. If an updated
191191
document is identical to the original, it is not included in this
192192
count.
193193

194194
* - ``wasAcknowledged()``
195195
- | Returns ``true`` if the server acknowledged the result.
196196

197197
* - ``getUpsertedId()``
198-
- | Specifies the ``_id`` value of the document that was upserted
198+
- | Returns the ``_id`` value of the document that was upserted
199199
in the database, if the driver performed an upsert.
200200

201201
.. note::
@@ -209,7 +209,7 @@ an ``UpdateResult`` instance:
209209
Additional Information
210210
----------------------
211211

212-
To view runnable code examples that demonstrate how to updates documents by
212+
To view runnable code examples that demonstrate how to update documents by
213213
using the {+driver-short+}, see :ref:`kotlin-sync-write`.
214214

215215
API Documentation

0 commit comments

Comments
 (0)