-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdb.collection.update.txt
1512 lines (1089 loc) · 44.9 KB
/
db.collection.update.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
.. _collection-update:
======================
db.collection.update()
======================
.. default-domain:: mongodb
.. meta::
:keywords: deprecated
:description: The update method is deprecated should be replaced by updateOne or updateMany.
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. include:: /includes/fact-mongosh-shell-method-deprecated.rst
Definition
----------
.. method:: db.collection.update(query, update, options)
Modifies an existing document or documents in a collection. The
method can modify specific fields of an existing document or documents
or replace an existing document entirely, depending on the
:ref:`update parameter <update-parameter>`.
By default, the :method:`db.collection.update()` method updates a
**single** document. Include the option :ref:`multi: true <multi-parameter>`
to update all documents that match the query criteria.
Compatibility
-------------
.. |operator-method| replace:: ``db.collection.update()``
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:: 5.0
The :method:`db.collection.update()` method has the following form:
.. code-block:: javascript
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>,
let: <document> // Added in MongoDB 5.0
}
)
.. _update-parameters:
Parameters
~~~~~~~~~~
The :method:`db.collection.update()` method takes the following
parameters:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - :ref:`query <update-query>`
- document
- .. _update-query:
The selection criteria for the update. The same :ref:`query
selectors <query-selectors>` as in the :method:`find()
<db.collection.find()>` method are available.
.. include:: /includes/fact-upsert-id.rst
:end-before: end-short-description
* - :ref:`update <update-parameter>`
- document or pipeline
- .. _update-parameter:
The modifications to apply. Can be one of the following:
.. list-table::
:widths: 40 80
:class: border-table
* - :ref:`Update document <update-method-update-document>`
- .. _update-method-update-document:
Contains only :ref:`update operator expressions
<update-operators>`.
* - :ref:`Replacement document
<update-method-replacement-document>`
- .. _update-method-replacement-document:
Contains only ``<field1>: <value1>`` pairs.
* - :ref:`Aggregation pipeline <update-method-agg-pipeline>`
- .. _update-method-agg-pipeline:
Contains only the following aggregation stages:
.. include:: /includes/list-update-agg-stages.rst
For details and examples, see :ref:`update-method-examples`.
* - :ref:`upsert <update-upsert>`
- boolean
- .. _update-upsert:
.. include:: /includes/extracts/update-upsert-behavior-method.rst
* - :ref:`multi <update-multi>`
- boolean
- .. _update-multi:
Optional. If set to ``true``, updates multiple documents that
meet the ``query`` criteria. If set to ``false``, updates one
document. The default value is ``false``. For additional
information, see :ref:`Update Multiple Documents Examples
<multi-parameter>`.
* - :ref:`writeConcern <update-wc>`
- document
- .. _update-wc:
Optional. A document expressing the :ref:`write concern
<write-concern>`. Omit to use the default write concern
``w: "majority"``.
.. include:: /includes/extracts/transactions-operations-write-concern.rst
For an example using ``writeConcern``, see
:ref:`example-update-write-concern`.
* - :ref:`collation <update-collation>`
- document
- .. _update-collation:
Optional.
.. include:: /includes/extracts/collation-description.rst
For an example using ``collation``, see
:ref:`example-update-collation`.
* - :ref:`arrayFilters <update-array-filters>`
- array
- .. _update-array-filters:
Optional. An array of filter documents that determine which array
elements to modify for an update operation on an array field.
In the :ref:`update document <update-parameter>`, use the
:update:`$[\<identifier\>]` to define an identifier to update
only those array elements that match the corresponding filter
document in the ``arrayFilters``.
You cannot have an array filter document for an identifier if
the identifier is not included in the update document.
For examples, see :ref:`update-arrayFilters`.
* - :ref:`hint <update-hint>`
- Document or string
- .. _update-hint:
Optional. A document or string that specifies the :ref:`index
<indexes>` to use to support the :ref:`query predicate
<update-query>`.
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-hint`.
* - :ref:`let <db.collection.update-let-syntax>`
- document
- .. _db.collection.update-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:`db.collection.update-let-example`.
.. versionadded:: 5.0
Returns
~~~~~~~
The method returns a :ref:`writeresults-update` document that contains
the status of the operation.
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.
.. _update-behavior:
Behavior
--------
Using ``$expr`` in an Update with ``Upsert``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Attempting to use the :manual:`$expr </reference/operator/query/expr/>`
operator with the upsert flag set to ``true`` will generate an error.
.. _update-sharded-collection:
Sharded Collections
~~~~~~~~~~~~~~~~~~~
To use :method:`db.collection.update()` with ``multi: false`` on a
sharded collection, you must include an exact match on the ``_id``
field or target a single shard (such as by including the shard key).
When the :method:`db.collection.update()` performs update operations
(and not document replacement operations),
:method:`db.collection.update()` can target multiple shards.
.. seealso::
:method:`~db.collection.findAndModify()`
Replace Document Operations on a Sharded Collection
```````````````````````````````````````````````````
Replace document operations attempt 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.
.. _method-update-sharded-upsert:
``upsert`` on a Sharded Collection
``````````````````````````````````
For a :method:`db.collection.update()` operation that includes
:ref:`upsert: true <update-upsert>` and is on a sharded collection, you
must include the full shard key in the ``filter``:
- For an update operation.
- For a replace document operation.
.. include:: /includes/extracts/missing-shard-key-equality-condition-update.rst
.. _method-update-shard-key-modification:
Shard Key Modification
``````````````````````
.. include:: /includes/limits-sharding-shardkey-document-immutable.rst
To modify the **existing** shard key value with
:method:`db.collection.update()`:
- 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 :ref:`transaction
<transactions>` or as a :ref:`retryable write
<retryable-writes>`.
- You :red:`must` specify ``multi: false``.
- You :red:`must` include an equality :ref:`query filter
<update-query>` on the full shard key.
.. tip::
.. include:: /includes/extracts/missing-shard-key-equality-condition-abridged.rst
See also :ref:`method-update-sharded-upsert`.
.. _method-update-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.update()` 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``
- - Can specify ``multi: true``.
- 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>`.
- :red:`Must` specify ``multi: false``.
- Requires equality filter on the full shard key if either:
- ``upsert: true``, or
- if using a replacement document and the new shard key
value belongs to a different shard.
.. tip::
.. include:: /includes/extracts/missing-shard-key-equality-condition-abridged.rst
See also:
- :ref:`method-update-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.update()`
.. _update-method-examples:
.. _update-behavior-operator-expressions-document:
.. _multi-parameter:
.. _example-update-specific-fields:
.. _example-update-replace-fields:
.. _update-behavior-replacement-document:
Oplog Entries
~~~~~~~~~~~~~
If a ``db.collection.update()`` operation successfully updates one or
more documents, the operation adds an entry on the :term:`oplog`
(operations log). If the operation fails or does not find any documents
to update, the operation does not add an entry on the oplog.
Examples
--------
The following tabs showcase a variety of common
:method:`~db.collection.update()` operations.
.. include:: /includes/fact-update-example-docs-intro.rst
.. include:: /includes/fact-update-example-docs.rst
.. tabs::
.. tab:: Set
:tabid: op-expr
Use Update Operator Expressions (``$inc`` and ``$set``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the ``<update>`` document contains :ref:`update operator
<update-operators>` modifiers, such as those using the
:update:`$set` modifier, then:
- The ``<update>`` document must contain *only*
:ref:`update operator <update-operators>` expressions.
- The :method:`db.collection.update()` method updates only the
corresponding fields in the document.
- To update an embedded document or an array as a whole,
specify the replacement value for the field.
- To update particular fields in an embedded document or in
an array, use :ref:`dot notation <document-dot-notation>`
to specify the field.
.. code-block:: javascript
db.books.update(
{ _id: 1 },
{
$inc: { stock: 5 },
$set: {
item: "ABC123",
"info.publisher": "2222",
tags: [ "software" ],
"ratings.1": { by: "xyz", rating: 3 }
}
}
)
In this operation:
- The ``<query>`` parameter of ``{ _id: 1 }`` specifies which
document to update,
- the :update:`$inc` operator increments the ``stock`` field,
and
- the :update:`$set` operator replaces the value of the
- ``item`` field,
- ``publisher`` field in the ``info`` embedded document,
- ``tags`` field, and
- second element in the ``ratings`` array.
The updated document is the following:
.. code-block:: javascript
:emphasize-lines: 2,4-6
{
"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : { "publisher" : "2222", "pages" : 430 },
"tags" : [ "software" ],
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : false
}
This operation corresponds to the following SQL statement:
.. code-block:: sql
UPDATE books
SET stock = stock + 5
item = "ABC123"
publisher = 2222
pages = 430
tags = "software"
rating_authors = "ijk,xyz"
rating_values = "4,3"
WHERE _id = 1
If the ``query`` parameter matches multiple documents,
the operation only updates one matching document. To
update multiple documents, set the ``multi`` option
to ``true``.
.. seealso::
:update:`$set`, :update:`$inc`,
:ref:`update operators <update-operators>`
:ref:`dot notation <document-dot-notation>`
.. tab:: Arrays
:tabid: push-elements-existing-array
Push Elements to Existing Array (``$push``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following operation uses the :update:`$push` update
operator to append a new object to the ``ratings`` array.
.. code-block:: javascript
db.books.update(
{ _id: 2 },
{
$push: { ratings: { "by" : "jkl", "rating" : 2 } }
}
)
The updated document is the following:
.. code-block:: javascript
:emphasize-lines: 12
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 15,
"info" : {
"publisher" : "5555",
"pages" : 150
},
"tags" : [ ],
"ratings" : [
{ "by" : "xyz", "rating" : 5 },
{ "by" : "jkl", "rating" : 2 }
],
"reorder" : false
}
.. seealso::
:update:`$push`
.. tab:: Unset
:tabid: remove-fields
Remove Fields (``$unset``)
~~~~~~~~~~~~~~~~~~~~~~~~~~
The following operation uses the :update:`$unset` operator to remove
the ``tags`` field from the document with ``{ _id: 1 }``.
.. code-block:: javascript
db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )
The updated document is the following:
.. code-block:: javascript
{
"_id" : 1,
"item" : "TBD",
"stock" : 0,
"info" : {
"publisher" : "1111",
"pages" : 430
},
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
"reorder" : false
}
There is not a direct SQL equivalent to :update:`$unset`,
however :update:`$unset` is similar to the following SQL
command which removes the ``tags`` field from the ``books``
table:
.. code-block:: sql
ALTER TABLE books
DROP COLUMN tags
.. seealso::
:update:`$unset`, :update:`$rename`, :ref:`update operators <update-operators>`
.. tab:: Multiple
:tabid: update-multiple
Update Multiple Documents (``$update`` With ``multi``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If ``multi`` is set to ``true``, the
:method:`db.collection.update()` method updates *all* documents
that meet the ``<query>`` criteria. The ``multi`` update
operation may interleave with other read/write operations.
The following operation sets the ``reorder`` field to ``true``
for all documents where ``stock`` is less than or equal to
``10``. If the ``reorder`` field does not exist in the matching
document(s), the :update:`$set` operator adds the field
with the specified value.
.. code-block:: javascript
db.books.update(
{ stock: { $lte: 10 } },
{ $set: { reorder: true } },
{ multi: true }
)
The resulting documents in the collection are the following:
.. code-block:: javascript
:emphasize-lines: 11,19
[
{
"_id" : 1,
"item" : "ABC123",
"stock" : 5,
"info" : {
"publisher" : "2222",
"pages" : 430
},
"ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
"reorder" : true
}
{
"_id" : 2,
"item" : "XYZ123",
"stock" : 10,
"info" : { "publisher" : "2255", "pages" : 150 },
"tags" : [ "baking", "cooking" ],
"reorder" : true
}
]
This operation corresponds to the following SQL statement:
.. code-block:: sql
UPDATE books
SET reorder=true
WHERE stock <= 10
You cannot specify ``multi: true`` when performing a replacement
and the :ref:`update <update-parameter>` document contains *only*
``field:value`` expressions.
.. seealso::
:update:`$set`
.. _example-update-upsert:
.. _upsert-parameter:
.. _upsert-behavior:
Insert a New Document if No Match Exists (``Upsert``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When you specify the option :ref:`upsert: true <update-upsert>`:
- If document(s) match the query criteria,
:method:`db.collection.update()` performs an update.
- If no document matches the query criteria,
:method:`db.collection.update()` inserts a *single* document.
.. note::
If multiple, identical :term:`upserts <upsert>` are issued at
roughly the same time, it is possible for
:method:`~db.collection.update()` used with :ref:`upsert: true
<update-upsert>` to create duplicate documents. See
:ref:`update-with-unique-indexes` for more information.
If you specify ``upsert: true`` on a sharded collection, you must
include the full shard key in the ``filter``. For additional
:method:`db.collection.update()` behavior on a sharded collection, see
:ref:`update-sharded-collection`.
The following tabs showcase a variety of uses of the ``upsert`` modifier
with :method:`~db.collection.update()`.
.. tabs::
.. tab:: Replace
:tabid: upsert-example
Upsert with Replacement Document
````````````````````````````````
If no document matches the query criteria and the ``<update>``
parameter is a replacement document (i.e., contains only field
and value pairs), the update inserts a new document with the
fields and values of the replacement document.
- If you specify an ``_id`` field in either the query parameter
or replacement document, MongoDB uses that ``_id`` field in the
inserted document.
- If you do not specify an ``_id`` field in either the query
parameter or replacement document, MongoDB generates adds the
``_id`` field with a randomly generated :ref:`objectid`
value.
You cannot specify different ``_id`` field values in the
query parameter and replacement document. If you do, the
operation errors.
For example, the following update sets the :ref:`upsert
<upsert-parameter>` option to ``true``:
.. code-block:: javascript
:emphasize-lines: 8
db.books.update(
{ item: "ZZZ135" }, // Query parameter
{ $set:
{
item: "ZZZ135", stock: 5, tags: [ "database" ] // Replacement document
}
},
{ upsert: true } // Options
)
If no document matches the ``<query>`` parameter, the update
operation inserts a document with *only* the replacement
document. Because no ``_id`` field was specified in the
replacement document or query document, the operation creates a
new unique ``ObjectId`` for the new document's ``_id`` field.
You can see the ``upsert`` reflected in the :ref:`WriteResult
<writeresults-update>` of the operation:
.. code-block:: javascript
:copyable: false
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("5da78973835b2f1c75347a83")
})
The operation inserts the following document into the ``books``
collection (your :ref:`objectid` value will differ):
.. code-block:: javascript
{
"_id" : ObjectId("5da78973835b2f1c75347a83"),
"item" : "ZZZ135",
"stock" : 5,
"tags" : [ "database" ]
}
.. tab:: Set
:tabid: upsert-op-expr
Upsert with Operator Expressions (``$set``)
```````````````````````````````````````````
If no document matches the query criteria and the ``<update>``
parameter is a document with :ref:`update operator expressions
<update-operators>`, then the operation creates a base document
from the equality clauses in the ``<query>`` parameter and
applies the expressions from the ``<update>`` parameter.
:ref:`Comparison <query-projection-operators-top>` operations from
the ``<query>`` will not be included in the new document. If
the new document does not include the ``_id`` field, MongoDB
adds the ``_id`` field with an :ref:`objectid` value.
For example, the following update sets the :ref:`upsert
<upsert-parameter>` option to ``true``:
.. code-block:: javascript
db.books.update(
{ item: "BLP921" }, // Query parameter
{ // Update document
$set: { reorder: false },
$setOnInsert: { stock: 10 }
},
{ upsert: true } // Options
)
If no documents match the query condition, the operation
inserts the following document (your :ref:`objectid` value
will differ):
.. code-block:: javascript
{
"_id" : ObjectId("5da79019835b2f1c75348a0a"),
"item" : "BLP921",
"reorder" : false,
"stock" : 10
}
.. seealso::
:update:`$setOnInsert`
.. tab:: Aggregation
:tabid: agg-pipeline-upsert
Upsert using an Aggregation Pipeline
````````````````````````````````````
If the ``<update>`` parameter is an :ref:`aggregation pipeline
<update-behavior-agg-pipeline>`, the update creates a base
document from the equality clauses in the ``<query>``
parameter, and then applies the pipeline to the document to
create the document to insert. If the new document does not
include the ``_id`` field, MongoDB adds the ``_id`` field with
an :ref:`objectid` value.
For example, the following :ref:`upsert: true
<upsert-parameter>` operation specifies an aggregation pipeline that uses
- the :pipeline:`$replaceRoot` stage which can provide
somewhat similar behavior to a :update:`$setOnInsert`
update operator expression,
- the :pipeline:`$set` stage which can provide similar
behavior to the :update:`$set` update operator expression,
- the aggregation variable :variable:`NOW`, which resolves to
the current datetime and can provide similar behavior to the
:update:`$currentDate` update operator expression.
.. code-block:: javascript
db.books.update(
{ item: "MRQ014", ratings: [2, 5, 3] }, // Query parameter
[ // Aggregation pipeline
{ $replaceRoot: { newRoot: { $mergeObjects: [ { stock: 0 }, "$$ROOT" ] } } },
{ $set: { avgRating: { $avg: "$ratings" }, tags: [ "fiction", "murder" ], lastModified: "$$NOW" } }
],
{ upsert: true } // Options
)
If no document matches the ``<query>`` parameter, the
operation inserts the following document into the ``books``
collection (your :ref:`objectid` value will differ):
.. code-block:: javascript
{
"_id" : ObjectId("5e2921e0b4c550aad59d1ba9"),
"stock" : 0,
"item" : "MRQ014",
"ratings" : [ 2, 5, 3 ],
"avgRating" : 3.3333333333333335,
"tags" : [ "fiction", "murder" ],
"lastModified" : ISODate("2020-01-23T04:32:32.951Z")
}
.. seealso::
For additional examples of updates using
aggregation pipelines, see :ref:`update-behavior-agg-pipeline`.
.. tab:: Multiple
:tabid: combine-upsert-multi
Using ``upsert`` with ``multi`` (Match)
```````````````````````````````````````
From :binary:`~bin.mongosh`, insert the following
documents into a ``books`` collection:
.. code-block:: javascript
db.books.insertMany( [
{
_id: 5,
item: "RQM909",
stock: 18,
info: { publisher: "0000", pages: 170 },
reorder: true
},
{
_id: 6,
item: "EFG222",
stock: 15,
info: { publisher: "1111", pages: 72 },
reorder: true
}
] )
The following operation specifies both the ``multi`` option and
the ``upsert`` option. If matching documents exist, the
operation updates all matching documents. If no matching
documents exist, the operation inserts a new document.
.. code-block:: javascript
db.books.update(
{ stock: { $gte: 10 } }, // Query parameter
{ // Update document
$set: { reorder: false, tags: [ "literature", "translated" ] }
},
{ upsert: true, multi: true } // Options
)
The operation updates all matching documents and results in the
following:
.. code-block:: javascript
{
"_id" : 5,
"item" : "RQM909",
"stock" : 18,
"info" : { "publisher" : "0000", "pages" : 170 },
"reorder" : false,
"tags" : [ "literature", "translated" ]
}
{
"_id" : 6,
"item" : "EFG222",
"stock" : 15,
"info" : { "publisher" : "1111", "pages" : 72 },
"reorder" : false,
"tags" : [ "literature", "translated" ]
}
Using ``upsert`` with ``multi`` (No Match)
``````````````````````````````````````````
If the collection had *no* matching document, the operation
would result in the insertion of a single document using the
fields from both the ``<query>`` and the ``<update>``
specifications. For example, consider the following operation:
.. code-block:: javascript
db.books.update(
{ "info.publisher": "Self-Published" }, // Query parameter
{ // Update document
$set: { reorder: false, tags: [ "literature", "hardcover" ], stock: 25 }
},
{ upsert: true, multi: true } // Options
)
The operation inserts the following document into the ``books``
collection (your :ref:`objectid` value will differ):
.. code-block:: javascript
{
"_id" : ObjectId("5db337934f670d584b6ca8e0"),
"info" : { "publisher" : "Self-Published" },
"reorder" : false,
"stock" : 25,
"tags" : [ "literature", "hardcover" ]
}
.. tab:: Dotted ``_id``
:tabid: upsert-dotted-id
Upsert with Dotted ``_id`` Query
````````````````````````````````
.. include:: /includes/fact-upsert-id.rst
The ``WriteResult`` of the operation returns the following
error:
.. code-block:: javascript
:copyable: false
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 111,
"errmsg" : "field at '_id' must be exactly specified, field at sub-path '_id.name'found"
}
})