$setOnInsert

Definition

  • $setOnInsert
  • If an update operation with upsert: trueresults in an insert of a document, then $setOnInsertassigns the specified values to the fields in the document. If theupdate operation does not result in an insert,$setOnInsert does nothing.

You can specify the upsert option for either thedb.collection.update() ordb.collection.findAndModify() methods.

  1. db.collection.update(
  2. <query>,
  3. { $setOnInsert: { <field1>: <value1>, ... } },
  4. { upsert: true }
  5. )

To specify a <field> in an embedded document or in an array, usedot notation.

Example

A collection named products contains no documents.

Then, the following db.collection.update() with upsert:true inserts a new document.

  1. db.products.update(
  2. { _id: 1 },
  3. {
  4. $set: { item: "apple" },
  5. $setOnInsert: { defaultQty: 100 }
  6. },
  7. { upsert: true }
  8. )

MongoDB creates a new document with _id equal to 1 from the<query> condition, and then applies the $set and$setOnInsert operations to this document.

The products collection contains the newly-inserted document:

  1. { "_id" : 1, "item" : "apple", "defaultQty" : 100 }

If the db.collection.update() with upsert: true had found a matching document, then MongoDBperforms an update, applying the $set operation but ignoringthe $setOnInsert operation.

See also

db.collection.update(),db.collection.findAndModify()