-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdb.collection.updateOne.txt
1056 lines (713 loc) · 30.6 KB
/
db.collection.updateOne.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=========================
db.collection.updateOne()
=========================
.. meta::
:description: Update a single document that matches a specified filter.
.. facet::
:name: programming_language
:values: shell
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. include:: includes/wayfinding/mongosh-method-updateOne.rst
Definition
----------
.. method:: db.collection.updateOne(filter, update, options)
.. |dbcommand| replace:: :dbcommand:`update` command
Updates a single document within the collection based on the filter.
Compatibility
-------------
.. |operator-method| replace:: ``db.collection.updateOne()``
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
------
The :method:`~db.collection.updateOne()` method has the following syntax:
.. code-block:: javascript
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document>,
sort: <document>
}
)
Parameters
~~~~~~~~~~
The :method:`db.collection.updateOne()` method takes the following
parameters:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - :ref:`filter <update-one-filter>`
- document
- .. _update-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 update the first document returned in
the collection.
* - :ref:`update <update-one-update>`
- document or pipeline
- .. _update-one-update:
The modifications to apply. Can be one of the following:
.. list-table::
:widths: 40 80
:class: border-table
* - :ref:`Update document <update-one-method-update-document>`
- .. _update-one-method-update-document:
Contains only :ref:`update operator expressions
<update-operators>`.
For more information, see
:ref:`updateOne-behavior-update-expressions`
* - :ref:`Aggregation pipeline <update-one-method-agg-pipeline>`
- .. _update-one-method-agg-pipeline:
Contains only the following aggregation stages:
.. include:: /includes/list-update-agg-stages.rst
For more information, see
:ref:`updateOne-behavior-aggregation-pipeline`.
To update with a replacement document, see
:method:`db.collection.replaceOne()`.
* - ``upsert``
- boolean
- .. include:: /includes/extracts/updateOne-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
* - ``arrayFilters``
- array
- Optional. An array of filter documents that determine which array elements to
modify for an update operation on an array field.
.. include:: /includes/extracts/arrayFilters-details.rst
For examples, see :ref:`updateOne-arrayFilters`.
* - :ref:`hint <update-one-hint>`
- Document or string
- .. _update-one-hint:
Optional. A document or string that specifies the :ref:`index
<indexes>` to use to support the :ref:`query predicate
<update-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-update-one-hint`.
* - ``let``
- Document
- .. _updateOne-let-syntax:
Optional.
.. include:: /includes/let-variables-syntax.rst
.. include:: /includes/let-variables-syntax-note.rst
For a complete example using ``let`` and variables,
see :ref:`updateMany-let-example`.
* - ``sort``
- Document
- .. _updateOne-document-syntax:
Optional.
Determines which document the operation updates if the query
selects multiple documents. ``updateOne`` updates
the first document in the sort order specified by this argument.
.. include:: /includes/fact-sort-document-type.rst
.. include:: /includes/fact-sort-consistency.rst
See :ref:`sort-cursor-consistent-sorting` for more information.
.. versionadded:: 8.0
Returns
~~~~~~~
The method returns a document that contains:
- ``matchedCount`` containing the number of matched documents
- ``modifiedCount`` containing the number of modified documents
- ``upsertedId`` containing the ``_id`` for the upserted document
- ``upsertedCount`` containing the number of upserted documents
- A boolean ``acknowledged`` as ``true`` if the operation ran with
:term:`write concern` or ``false`` if write concern was disabled
Access Control
--------------
On deployments running with :setting:`~security.authorization`, the
user must have access that includes the following privileges:
- :authaction:`update` action on the specified collection(s).
- :authaction:`find` action on the specified collection(s).
- :authaction:`insert` action on the specified collection(s) if the
operation results in an upsert.
The built-in role :authrole:`readWrite` provides the required
privileges.
.. _updateOne-behavior:
Behavior
--------
Updates a Single Document
~~~~~~~~~~~~~~~~~~~~~~~~~
:method:`db.collection.updateOne()` finds the first document that
matches the :ref:`filter <update-one-filter>` and applies the specified
:ref:`update <update-one-update>` modifications.
.. _updateOne-behavior-update-expressions:
Update with an Update Operator Expressions Document
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For the :ref:`update specifications <update-one-update>`, the
:method:`db.collection.updateOne()` method can accept a document that
only contains :ref:`update operator <update-operators>` expressions.
For example:
.. code-block:: javascript
:emphasize-lines: 3
:copyable: false
db.collection.updateOne(
<query>,
{ $set: { status: "D" }, $inc: { quantity: 2 } },
...
)
.. _updateOne-behavior-aggregation-pipeline:
Update with an Aggregation Pipeline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :method:`db.collection.updateOne()` method can accept an
:ref:`aggregation pipeline <aggregation-pipeline>`
``[ <stage1>, <stage2>, ... ]`` that specifies the modifications to perform.
The pipeline can consist of the following stages:
.. include:: /includes/list-update-agg-stages.rst
Using the aggregation pipeline allows for a more expressive update
statement, such as expressing conditional updates based on current
field values or updating one field using the value of another field(s).
For example:
.. code-block:: javascript
:emphasize-lines: 3-6
:copyable: false
db.collection.updateOne(
<query>,
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
{ $unset: [ "misc1", "misc2" ] }
]
...
)
.. note::
The ``$set`` and ``$unset`` used in the pipeline refers to the
aggregation stages :pipeline:`$set` and :pipeline:`$unset`
respectively, and not the update operators :update:`$set` and :update:`$unset`.
For examples, see :ref:`updateOne-example-agg`.
Upsert
~~~~~~
- .. include:: /includes/fact-7-1-sharded-upsert.rst
- If ``upsert: true`` and no documents match the ``filter``,
:method:`db.collection.updateOne()` creates a new
document based on the ``filter`` criteria and ``update``
modifications. See :ref:`updateOne-example-update-with-upsert`.
- For additional :method:`db.collection.updateOne()` behavior on a
sharded collection, see :ref:`updateOne-sharded-collection`.
.. _updateOne-capped-collection:
Capped Collection
~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/capped-collection-immutable-document-size-update.rst
.. _updateOne-sharded-collection:
Sharded Collections
~~~~~~~~~~~~~~~~~~~
.. _updateOne-sharded-upsert:
``upsert`` on a Sharded Collection
``````````````````````````````````
To use :method:`db.collection.updateOne()` on a sharded collection:
- .. include:: /includes/fact-7-1-sharded-upsert.rst
- If you don't specify ``upsert: true``, you must include an exact
match on the ``_id`` field or target a single shard (such as by
including the shard key in the :ref:`filter <update-one-filter>`).
.. include:: /includes/extracts/missing-shard-key-equality-condition-update.rst
.. _updateOne-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.updateOne()`:
- 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
<update-one-filter>` on the full shard key.
See also :ref:`updateOne-sharded-upsert`.
.. _updateOne-missing-shard-key:
Missing Shard Key
`````````````````
- Starting in version 7.1, you do not need to provide the :term:`shard key`
or ``_id`` field in the query specification.
- Documents in a sharded collection can be
:ref:`missing the shard key fields <shard-key-missing>`. To use
:method:`db.collection.updateOne()` to set a **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``.
* - To set to a non-``null`` value
- :red:`Must` be performed either inside a
:ref:`transaction <transactions>` or as a
:ref:`retryable write <retryable-writes>`.
Requires equality filter on the full shard key if ``upsert: true``.
.. tip::
.. include:: /includes/extracts/missing-shard-key-equality-condition-abridged.rst
See also:
- :ref:`updateOne-sharded-upsert`
- :ref:`shard-key-missing`
Explainability
~~~~~~~~~~~~~~
:method:`~db.collection.updateOne()` is not compatible with
:method:`db.collection.explain()`.
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.updateOne()`
Oplog Entries
~~~~~~~~~~~~~
If a ``db.collection.updateOne()`` operation successfully updates a
document, the operation adds an entry on the :term:`oplog` (operations
log). If the operation fails or does not find a document to update, the
operation does not add an entry on the oplog.
.. _updateOne-method-examples:
Examples
--------
.. _updateOne-example-update:
Update using Update Operator Expressions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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 updates a single document where
``name: "Central Perk Cafe"`` with the ``violations`` field:
.. code-block:: javascript
try {
db.restaurant.updateOne(
{ "name" : "Central Perk Cafe" },
{ $set: { "violations" : 3 } }
);
} 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:`updateOne-example-update-with-upsert`
.. _updateOne-example-agg:
Update with Aggregation Pipeline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The :method:`db.collection.updateOne()` can use an aggregation pipeline for the
update. The pipeline can consist of the following stages:
.. include:: /includes/list-update-agg-stages.rst
Using the aggregation pipeline allows for a more expressive update
statement, such as expressing conditional updates based on current
field values or updating one field using the value of another field(s).
Example 1
`````````
The following examples uses the aggregation pipeline to modify a field
using the values of the other fields in the document.
Create a ``students`` collection with the following documents:
.. code-block:: javascript
db.students.insertMany( [
{ "_id" : 1, "student" : "Skye", "points" : 75, "commentsSemester1" : "great at math", "commentsSemester2" : "loses temper", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "student" : "Elizabeth", "points" : 60, "commentsSemester1" : "well behaved", "commentsSemester2" : "needs improvement", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )
Assume that instead of separate ``commentsSemester1`` and ``commentsSemester2``
fields in the first document, you want to gather these into a ``comments`` field,
like the second document. The following update operation uses an
aggregation pipeline to:
- add the new ``comments`` field and set the ``lastUpdate`` field.
- remove the ``commentsSemester1`` and ``commentsSemester2`` fields for all
documents in the collection.
Make sure that the filter in the update command targets a unique document. The
field ``id`` in the code below is an example of such a filter:
.. code-block:: javascript
db.students.updateOne(
{ _id: 1 },
[
{ $set: { status: "Modified", comments: [ "$commentsSemester1", "$commentsSemester2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "commentsSemester1", "commentsSemester2" ] }
]
)
.. note::
The ``$set`` and ``$unset`` used in the pipeline refers to the
aggregation stages :pipeline:`$set` and :pipeline:`$unset`
respectively, and not the update operators :update:`$set` and :update:`$unset`.
First Stage
The :pipeline:`$set` stage:
- creates a new array field ``comments`` whose elements are the current
content of the ``misc1`` and ``misc2`` fields and
- sets the field ``lastUpdate`` to the value of the aggregation
variable :variable:`NOW`. The aggregation variable
:variable:`NOW` resolves to the current datetime value and remains
the same throughout the pipeline. To access aggregation
variables, prefix the variable with double dollar signs ``$$``
and enclose in quotes.
Second Stage
The :pipeline:`$unset` stage removes the ``commentsSemester1`` and
``commentsSemester2`` fields.
After the command, the collection contains the following documents:
.. code-block:: javascript
:copyable: false
{ "_id" : 2, "student" : "Elizabeth", "status" : "Modified", "points" : 60, "lastUpdate" : ISODate("2020-01-23T05:11:45.784Z"), "comments" : [ "well behaved", "needs improvement" ] }
{ _id: 1, student: 'Skye', points: 75, commentsSemester1: 'great at math', commentsSemester2: 'loses temper', lastUpdate: ISODate("2019-01-01T00:00:00.000Z") }
Note that after introducing a sort, only the first document encountered in the
sort order is modified and the remaining documents are left untouched.
Example 2
`````````
The aggregation pipeline allows the update to perform conditional
updates based on the current field values as well as use current field
values to calculate a separate field value.
For example, create a ``students3`` collection with the following documents:
.. code-block:: javascript
db.students3.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "average" : 92, "grade" : "A", "lastUpdate" : ISODate("2020-01-23T05:18:40.013Z") },
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "average" : 91, "grade" : "A", "lastUpdate" : ISODate("2020-01-23T05:18:40.013Z") },
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )
The third document ``_id: 3`` is missing the ``average`` and ``grade``
fields. Using an aggregation pipeline, you can update the document with
the calculated grade average and letter grade.
.. code-block:: javascript
db.students3.updateOne(
{ _id: 3 },
[
{ $set: { average: { $trunc: [ { $avg: "$tests" }, 0 ] }, lastUpdate: "$$NOW" } },
{ $set: { grade: { $switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
} } } }
]
)
.. note::
The ``$set`` used in the pipeline refers to the aggregation stage
:pipeline:`$set`, and not the update operators :update:`$set`.
First Stage
The :pipeline:`$set` stage:
- calculates a new field ``average`` based on the average of the
``tests`` field. See :group:`$avg` for more information on the
``$avg`` aggregation operator and :expression:`$trunc` for more
information on the ``$trunc`` truncate aggregation operator.
- sets the field ``lastUpdate`` to the value of the aggregation
variable :variable:`NOW`. The aggregation variable
:variable:`NOW` resolves to the current datetime value and remains
the same throughout the pipeline. To access aggregation
variables, prefix the variable with double dollar signs ``$$``
and enclose in quotes.
Second Stage
The :pipeline:`$set` stage calculates a new field ``grade`` based on
the ``average`` field calculated in the previous stage. See
:expression:`$switch` for more information on the ``$switch``
aggregation operator.
After the command, the collection contains the following documents:
.. code-block:: javascript
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "average" : 92, "grade" : "A", "lastUpdate" : ISODate("2020-01-23T05:18:40.013Z") }
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "average" : 91, "grade" : "A", "lastUpdate" : ISODate("2020-01-23T05:18:40.013Z") }
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2020-01-24T17:33:30.674Z"), "average" : 75, "grade" : "C" }
.. seealso::
:doc:`/tutorial/update-documents-with-aggregation-pipeline`
.. _updateOne-example-update-with-upsert:
Update 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 update the document with
``name : "Pizza Rat's Pizzaria"``, while ``upsert: true`` :
.. code-block:: javascript
try {
db.restaurant.updateOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } },
{ upsert: true }
);
} catch (e) {
print(e);
}
Since ``upsert:true`` the document is ``inserted`` based on the ``filter`` and
``update`` criteria. The operation returns:
.. code-block:: javascript
{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : 4,
"upsertedCount": 1
}
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" : 4 },
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 7 }
The ``name`` field was filled in using the ``filter`` criteria, while the
``update`` operators were used to create the rest of the document.
The following operation updates the first document with ``violations`` that
are greater than ``10``:
.. code-block:: javascript
try {
db.restaurant.updateOne(
{ "violations" : { $gt: 10} },
{ $set: { "Closed" : true } },
{ upsert: true }
);
} catch (e) {
print(e);
}
The operation returns:
.. code-block:: javascript
{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : ObjectId("56310c3c0c5cbb6031cafaea")
}
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" : 4 },
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "grade" : 7 }
{ "_id" : ObjectId("56310c3c0c5cbb6031cafaea"), "Closed" : true }
Since no documents matched the filter, and ``upsert`` was ``true``,
:method:`~db.collection.updateOne` inserted the document with a generated
``_id`` and the ``update`` criteria only.
.. _updateOne-example-update-with-write-concern:
Update with Write Concern
~~~~~~~~~~~~~~~~~~~~~~~~~
Given a three member replica set, the following operation specifies a
``w`` of ``majority``, ``wtimeout`` of ``100``:
.. code-block:: javascript
try {
db.restaurant.updateOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ $inc: { "violations" : 3}, $set: { "Closed" : true } },
{ w: "majority", wtimeout: 100 }
);
} catch (e) {
print(e);
}
If the primary and at least one secondary acknowledge each write operation
within 100 milliseconds, it returns:
.. code-block:: javascript
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
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
Update with Sort
~~~~~~~~~~~~~~~~
.. versionadded:: 8.0
The following example deactivates the lowest rated active user:
.. code-block:: javascript
db.people.updateOne(
{ state: "active" },
{ $set: { state: "inactive" } },
{ sort: { rating: 1 }
)
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.updateOne(
{ category: "cafe" },
{ $set: { status: "Updated" } },
{ collation: { locale: "fr", strength: 1 } }
);
.. _updateOne-arrayFilters:
Specify ``arrayFilters`` for an Array Update Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/arrayFilters-blurb.rst
Update Elements Match ``arrayFilters`` Criteria
```````````````````````````````````````````````
Create a collection ``students`` with the following documents:
.. code-block:: javascript
db.students.insertMany( [
{ "_id" : 1, "grades" : [ 95, 92, 90 ] },
{ "_id" : 2, "grades" : [ 98, 100, 102 ] },
{ "_id" : 3, "grades" : [ 95, 110, 100 ] }
] )
To modify all elements that are greater than or equal to ``100`` in the
``grades`` array, use the filtered positional operator
:update:`$[\<identifier\>]` with the ``arrayFilters`` option in the
:method:`db.collection.updateOne` method:
.. code-block:: javascript
db.students.updateOne(
{ grades: { $gte: 100 } },
{ $set: { "grades.$[element]" : 100 } },
{ arrayFilters: [ { "element": { $gte: 100 } } ] }
)
The operation updates the ``grades`` field of a single document, and
after the operation, the collection has the following documents:
.. code-block:: javascript
:emphasize-lines: 2
{ "_id" : 1, "grades" : [ 95, 92, 90 ] }
{ "_id" : 2, "grades" : [ 98, 100, 100 ] }
{ "_id" : 3, "grades" : [ 95, 110, 100 ] }
Update Specific Elements of an Array of Documents
`````````````````````````````````````````````````
Create a collection ``students2`` with the following documents:
.. code-block:: javascript
db.students2.insertMany( [
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 90, "std" : 4 },
{ "grade" : 85, "mean" : 85, "std" : 6 }
]
},
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 6 },
{ "grade" : 87, "mean" : 90, "std" : 3 },
{ "grade" : 85, "mean" : 85, "std" : 4 }
]
}
] )
To modify the value of the ``mean`` field for all elements in the
``grades`` array where the grade is greater than or equal to ``85``,
use the filtered positional operator :update:`$[\<identifier\>]` with
the ``arrayFilters`` in the :method:`db.collection.updateOne` method:
.. code-block:: javascript
db.students2.updateOne(
{ },
{ $set: { "grades.$[elem].mean" : 100 } },
{ arrayFilters: [ { "elem.grade": { $gte: 85 } } ] }
)
The operation updates the array of a single document, and after the
operation, the collection has the following documents:
.. code-block:: javascript
:emphasize-lines: 5-6
{
"_id" : 1,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 6 },
{ "grade" : 85, "mean" : 100, "std" : 4 },
{ "grade" : 85, "mean" : 100, "std" : 6 }
]
}
{
"_id" : 2,
"grades" : [
{ "grade" : 90, "mean" : 75, "std" : 6 },
{ "grade" : 87, "mean" : 90, "std" : 3 },
{ "grade" : 85, "mean" : 85, "std" : 4 }
]
}
.. _ex-update-one-hint:
Specify ``hint`` for Update Operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a sample ``students`` collection with the following documents:
.. code-block:: javascript
db.students.insertMany( [
{ "_id" : 1, "student" : "Richard", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 2, "student" : "Jane", "grade" : "A", "points" : 60, "comments1" : "well behaved", "comments2" : "fantastic student" },
{ "_id" : 3, "student" : "Ronan", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 4, "student" : "Noah", "grade" : "D", "points" : 20, "comments1" : "needs improvement", "comments2" : null },
{ "_id" : 5, "student" : "Adam", "grade" : "F", "points" : 0, "comments1" : null, "comments2" : null },
{ "_id" : 6, "student" : "Henry", "grade" : "A", "points" : 86, "comments1" : "fantastic student", "comments2" : "well behaved" }
] )
Create the following indexes on the collection:
.. code-block:: javascript
db.students.createIndex( { grade: 1 } )
db.students.createIndex( { points: 1 } )
The following update operation explicitly hints to use the index ``{
grade: 1 }``:
.. note::
If you specify an index that does not exist, the operation errors.
.. code-block:: javascript
db.students.updateOne(
{ "points": { $lte: 20 }, "grade": "F" },
{ $set: { "comments1": "failed class" } },
{ hint: { grade: 1 } }
)
The update command returns the following: