-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdb.collection.replaceOne.txt
537 lines (356 loc) · 14.5 KB
/
db.collection.replaceOne.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
==========================
db.collection.replaceOne()
==========================
.. default-domain:: mongodb
.. meta::
:description: Replace a matched document with a new document.
.. facet::
:name: programming_language
:values: shell
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. include:: includes/wayfinding/mongosh-method-replaceOne.rst
Definition
----------
.. method:: db.collection.replaceOne(filter, replacement, options)
.. |dbcommand| replace:: :dbcommand:`update` command
Replaces a single document within the collection based on the filter.
:returns:
A document containing:
- A boolean ``acknowledged`` as ``true`` if the operation ran with
:term:`write concern` or ``false`` if write concern was disabled
- ``matchedCount`` containing the number of matched documents
- ``modifiedCount`` containing the number of modified documents
- ``upsertedId`` containing the ``_id`` for the upserted document
Compatibility
-------------
.. |operator-method| replace:: ``db.collection.replaceOne()``
This method is available in deployments hosted in the following environments:
.. include:: /includes/fact-environments-atlas-only.rst
.. include:: /includes/fact-environments-atlas-support-all.rst
.. include:: /includes/fact-environments-onprem-only.rst
Syntax
------
.. versionchanged:: 8.0
The :method:`~db.collection.replaceOne()` method has the following form:
.. code-block:: javascript
db.collection.replaceOne(
<filter>,
<replacement>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
hint: <document|string>,
sort: <document>
}
)
The :method:`~db.collection.replaceOne()` method takes the following
parameters:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - :ref:`filter <replace-one-filter>`
- document
- .. _replace-one-filter:
The selection criteria for the update. The same :ref:`query
selectors <query-selectors>` as in the :method:`find()
<db.collection.find()>` method are available.
Specify an empty document ``{ }`` to replace the first document returned in
the collection.
* - ``replacement``
- document
- The replacement document.
Cannot contain :ref:`update operators <update-operators-top-level>`.
* - ``upsert``
- boolean
- .. include:: /includes/extracts/replaceOne-behavior-method.rst
* - ``writeConcern``
- document
- Optional. A document expressing the :doc:`write concern
</reference/write-concern>`. Omit to use the default write concern.
.. include:: /includes/extracts/transactions-operations-write-concern.rst
* - ``collation``
- document
- Optional.
.. include:: /includes/extracts/collation-option.rst
* - :ref:`hint <replace-one-hint>`
- document
- .. _replace-one-hint:
Optional. A document or string that specifies the :ref:`index
<indexes>` to use to support the :ref:`filter
<replace-one-filter>`.
The option can take an index specification document or the index
name string.
If you specify an index that does not exist, the operation
errors.
For an example, see :ref:`ex-replace-one-hint`.
* - ``sort``
- document
- .. _replace-one-sort-syntax:
.. include:: /includes/sort-update-field.rst
For an example, see :ref:`replaceOne-example-sort`.
Behavior
--------
:method:`~db.collection.replaceOne()` replaces the first matching document in
the collection that matches the ``filter``, using the ``replacement``
document.
``upsert``
~~~~~~~~~~
If ``upsert: true`` and no documents match the ``filter``,
:method:`db.collection.replaceOne()` creates a new document based on
the ``replacement`` document.
If you specify ``upsert: true`` on a sharded collection, you must
include the full shard key in the ``filter``. For additional
:method:`db.collection.replaceOne()` behavior on a sharded collection,
see :ref:`replaceOne-sharded-collection`.
See :ref:`replaceOne-example-replace-with-upsert`.
.. _replaceOne-capped-collection:
Capped Collections
~~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/capped-collection-immutable-document-size-replace.rst
.. _replaceOne-timeseries-collection:
Time Series Collections
~~~~~~~~~~~~~~~~~~~~~~~
You cannot use the :method:`~db.collection.replaceOne()` method on a
:term:`time series collection`.
.. _replaceOne-sharded-collection:
Sharded Collections
~~~~~~~~~~~~~~~~~~~
:method:`db.collection.replaceOne()` attempts to target a single shard, first by
using the query filter. If the operation cannot target a single shard by the
query filter, it then attempts to target by the replacement document.
In earlier versions, the operation attempts to target using the
replacement document.
Shard Key Requirements In Replacement Document
``````````````````````````````````````````````
The replacement document does not need to include the shard key.
.. include:: /includes/shard-key-modification-warning.rst
.. _replaceOne-sharded-upsert:
``upsert`` on a Sharded Collection
``````````````````````````````````
A :method:`db.collection.replaceOne()` operation that includes ``upsert: true``
on a sharded collection must include the full shard key in the ``filter``.
.. include:: /includes/extracts/missing-shard-key-equality-condition-update.rst
.. _replaceOne-shard-key-modification:
Shard Key Modification
``````````````````````
.. include:: /includes/limits-sharding-shardkey-document-immutable.rst
.. include:: /includes/shard-key-modification-warning.rst
To modify the **existing** shard key value with
:method:`db.collection.replaceOne()`:
- You :red:`must` run on a :binary:`~bin.mongos`. Do :red:`not`
issue the operation directly on the shard.
- You :red:`must` run either in a :doc:`transaction
</core/transactions>` or as a :doc:`retryable write
</core/retryable-writes>`.
- You :red:`must` include an equality :ref:`filter
<replace-one-filter>` on the full shard key.
.. _replaceOne-missing-shard-key:
Missing Shard Key
`````````````````
Documents in a sharded collection can be
:ref:`missing the shard key fields <shard-key-missing>`. To use
:method:`db.collection.replaceOne()` to set the document's
**missing** shard key, you :red:`must` run on a
:binary:`~bin.mongos`. Do :red:`not` issue the operation directly on
the shard.
In addition, the following requirements also apply:
.. list-table::
:header-rows: 1
:widths: 30 70
* - Task
- Requirements
* - To set to ``null``
- - Requires equality filter on the full shard key if ``upsert:
true`` is specified.
* - To set to a non-``null`` value
- - :red:`Must` be performed either inside a :doc:`transaction
</core/transactions>` or as a :doc:`retryable write
</core/retryable-writes>`.
- Requires equality filter on the full shard key if either:
- ``upsert: true``, or
- the new shard key value belongs to a different shard.
.. tip::
.. include:: /includes/extracts/missing-shard-key-equality-condition-abridged.rst
See also:
- :ref:`replaceOne-sharded-upsert`
- :ref:`shard-key-missing`
Transactions
~~~~~~~~~~~~
.. include:: /includes/extracts/transactions-supported-operation.rst
.. include:: /includes/extracts/transactions-usage.rst
Upsert within Transactions
``````````````````````````
.. include:: /includes/extracts/transactions-upsert-availability.rst
Write Concerns and Transactions
````````````````````````````````
.. include:: /includes/extracts/transactions-operations-write-concern.rst
.. |operation| replace:: :method:`db.collection.replaceOne()`
Examples
--------
.. _replaceOne-example-update:
Replace
~~~~~~~
The ``restaurant`` collection contains the following documents:
.. code-block:: javascript
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }
The following operation replaces a single document where
``name: "Central Perk Cafe"``:
.. code-block:: javascript
try {
db.restaurant.replaceOne(
{ "name" : "Central Perk Cafe" },
{ "name" : "Central Pork Cafe", "Borough" : "Manhattan" }
);
} catch (e){
print(e);
}
The operation returns:
.. code-block:: javascript
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
If no matches were found, the operation instead returns:
.. code-block:: javascript
{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
Setting ``upsert: true`` would insert the document if no match was found. See
:ref:`replaceOne-example-replace-with-upsert`
.. _replaceOne-example-replace-with-upsert:
Replace with Upsert
~~~~~~~~~~~~~~~~~~~
The ``restaurant`` collection contains the following documents:
.. code-block:: javascript
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }
The following operation attempts to replace the document with
``name : "Pizza Rat's Pizzaria"``, with ``upsert : true``:
.. code-block:: javascript
try {
db.restaurant.replaceOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ "_id": 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 },
{ upsert: true }
);
} catch (e){
print(e);
}
Since ``upsert : true`` the document is inserted based on the
``replacement`` document. The operation returns:
.. code-block:: javascript
{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : 4
}
The collection now contains the following documents:
.. code-block:: javascript
{ "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
{ "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 },
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 8 }
.. _replaceOne-example-replace-with-write-concern:
Replace with Write Concern
~~~~~~~~~~~~~~~~~~~~~~~~~~
Given a three member replica set, the following operation specifies a
``w`` of ``majority`` and ``wtimeout`` of ``100``:
.. code-block:: javascript
try {
db.restaurant.replaceOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ "name" : "Pizza Rat's Pub", "Borough" : "Manhattan", "violations" : 3 },
{ w: "majority", wtimeout: 100 }
);
} catch (e) {
print(e);
}
If the acknowledgment takes longer than the ``wtimeout`` limit, the following
exception is thrown:
.. code-block:: javascript
WriteConcernError({
"code" : 64,
"errmsg" : "waiting for replication timed out",
"errInfo" : {
"wtimeout" : true,
"writeConcern" : {
"w" : "majority",
"wtimeout" : 100,
"provenance" : "getLastErrorDefaults"
}
}
})
The following table explains the possible values of
``errInfo.writeConcern.provenance``:
.. include:: /includes/fact-wc-provenance-table.rst
Specify Collation
~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/collation-versionadded.rst
A collection ``myColl`` has the following documents:
.. code-block:: javascript
{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }
The following operation includes the :ref:`collation <collation>`
option:
.. code-block:: javascript
db.myColl.replaceOne(
{ category: "cafe", status: "a" },
{ category: "cafÉ", status: "Replaced" },
{ collation: { locale: "fr", strength: 1 } }
);
.. _ex-replace-one-hint:
Specify ``hint`` for ``replaceOne``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a sample ``members`` collection with the following documents:
.. code-block:: javascript
db.members.insertMany([
{ "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
{ "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
{ "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
{ "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
])
Create the following indexes on the collection:
.. code-block:: javascript
db.members.createIndex( { status: 1 } )
db.members.createIndex( { points: 1 } )
The following update operation explicitly hints to use the index ``{
status: 1 }``:
.. note::
If you specify an index that does not exist, the operation errors.
.. code-block:: javascript
db.members.replaceOne(
{ "points": { $lte: 20 }, "status": "P" },
{ "misc1": "using index on status", status: "P", member: "replacement", points: "20"},
{ hint: { status: 1 } }
)
The operation returns the following:
.. code-block:: javascript
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
To view the indexes used, you can use the :pipeline:`$indexStats` pipeline:
.. code-block:: javascript
db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )
.. _replaceOne-example-sort:
Replace One Document and Use a Sort
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/restaurants-update-sort-example.rst
.. code-block:: javascript
:emphasize-lines: 9
db.restaurantsSort.replaceOne(
// Find restaurants with a rating of 4
{ rating: 4 },
// Replace the found restaurant with Clean Eats
{ name: "Clean Eats", rating: 4, violations: 2 },
// Sort restaurants found by the most violations with a descending sort
{ sort: { violations: -1 } }
)
.. include:: /includes/restaurants-update-sort-example-description-and-output.rst