- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $setOnInsert
$setOnInsert¶
On this page
-
$setOnInsert¶ New in version 2.4.
If an upsert results in an insert of a document, then
$setOnInsertassigns the specified values to the fields in the document. You can specify an upsert by specifying the upsert option for either thedb.collection.update()ordb.collection.findAndModify()methods. If the upsert results in an update,$setOnInserthas no effect.
Examples¶
Upsert Results in an Insert¶
A collection named products contains no documents.
Then, the following upsert
operation performs an insert and applies the
$setOnInsert to set the field defaultQty to
100:
The products collection contains the newly-inserted document:
Upsert Results in an Update¶
If the db.collection.update() or the
db.collection.findAndModify() method has the upsert flag
and performs an update and not an insert, $setOnInsert has no
effect.
A collection named products has the following document:
The following update() with the
upsert flag operation performs an update:
Because the update() with upsert only
performs an update, MongoDB ignores the $setOnInsert
operation and only applies the $set operation.
The products collection now contains the following modified
document: