OPTIONS

$setOnInsert

$setOnInsert

New in version 2.4.

If an upsert results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. You can specify an upsert by specifying the upsert option for either the db.collection.update() or db.collection.findAndModify() methods. If the upsert results in an update, $setOnInsert has no effect.

db.collection.update(
   <query>,
   { $setOnInsert: { <field1>: <value1>, ... } },
   { upsert: true }
)

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:

db.products.update(
  { _id: 1 },
  { $setOnInsert: { defaultQty: 100 } },
  { upsert: true }
)

The products collection contains the newly-inserted document:

{ "_id" : 1, "defaultQty" : 100 }

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:

{ "_id" : 1, "defaultQty" : 100 }

The following update() with the upsert flag operation performs an update:

db.products.update(
  { _id: 1 },
  {
    $setOnInsert: { defaultQty: 500, inStock: true },
    $set: { item: "apple" }
  },
  { upsert: true }
)

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:

{ "_id" : 1, "defaultQty" : 100, "item" : "apple" }
←   $rename $set  →