Skip to content

Commit 3e8a973

Browse files
committed
DOCSP-41819: replace document
1 parent ae8646c commit 3e8a973

File tree

4 files changed

+247
-4
lines changed

4 files changed

+247
-4
lines changed

source/includes/write/replace.kt

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

source/write-operations.txt

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

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

2930
..
30-
/write/replace
3131
/write/bulk-write
3232
/write/gridfs
3333

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

source/write/update.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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)