|
| 1 | +============ |
| 2 | +$setOnInsert |
| 3 | +============ |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +.. operator:: $setOnInsert |
| 8 | + |
| 9 | + .. versionadded:: 2.4 |
| 10 | + |
| 11 | + The :operator:`$setOnInsert` operator assigns values to fields |
| 12 | + during an :method:`upsert <db.collection.update()>` **only** when |
| 13 | + the :method:`upsert <db.collection.update()>` performs an insert. |
| 14 | + |
| 15 | + .. code-block:: javascript |
| 16 | + |
| 17 | + db.collection.update( <query>, |
| 18 | + { $setOnInsert: { <field1>: <value1>, ... } }, |
| 19 | + { upsert: true } |
| 20 | + ) |
| 21 | + .. example:: |
| 22 | + |
| 23 | + A collection named ``products`` contains no documents. |
| 24 | + |
| 25 | + Then, the following :method:`upsert <db.collection.update()>` |
| 26 | + operation performs an insert and applies the |
| 27 | + :operator:`$setOnInsert` to set the field ``defaultQty`` to |
| 28 | + ``100``: |
| 29 | + |
| 30 | + .. code-block:: javascript |
| 31 | + |
| 32 | + db.products.update( |
| 33 | + { _id: 1 }, |
| 34 | + { $setOnInsert: { defaultQty: 100 } }, |
| 35 | + { upsert: true } |
| 36 | + ) |
| 37 | + |
| 38 | + The ``products`` collection contains the newly-inserted document: |
| 39 | + |
| 40 | + .. code-block:: javascript |
| 41 | + |
| 42 | + { "_id" : 1, "defaultQty" : 100 } |
| 43 | + |
| 44 | + .. note:: |
| 45 | + |
| 46 | + The :operator:`$setOnInsert` operator performs no operation for |
| 47 | + :method:`upserts <db.collection.update()>` that only perform an |
| 48 | + update and for :method:`updates <db.collection.update()>` where |
| 49 | + ``upsert`` is not specified or is set to ``false``. |
| 50 | + |
| 51 | + .. example:: |
| 52 | + |
| 53 | + A collection named ``products`` has the following document: |
| 54 | + |
| 55 | + .. code-block:: javascript |
| 56 | + |
| 57 | + { "_id" : 1, "defaultQty" : 100 } |
| 58 | + |
| 59 | + The following :method:`upsert <db.collection.update()>` operation |
| 60 | + performs an update: |
| 61 | + |
| 62 | + .. code-block:: javascript |
| 63 | + |
| 64 | + db.products.update( |
| 65 | + { _id: 1 }, |
| 66 | + { $setOnInsert: { defaultQty: 500, inStock: true }, |
| 67 | + $set: { item: "apple" } }, |
| 68 | + { upsert: true } |
| 69 | + ) |
| 70 | + |
| 71 | + Because the :method:`upsert <db.collection.update()>` performs an |
| 72 | + update only, the upsert ignores the :operator:`$setOnInsert` |
| 73 | + operation and only applies the :operator:`$set` operation. |
| 74 | + |
| 75 | + The ``products`` collection contains the following modified |
| 76 | + document: |
| 77 | + |
| 78 | + .. code-block:: javascript |
| 79 | + |
| 80 | + { "_id" : 1, "defaultQty" : 100, "item" : "apple" } |
0 commit comments