Docs Menu

$setOnInsert

On this page

  • Definition
  • Behavior
  • Example
$setOnInsert

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

You can specify the upsert option for either the db.collection.update() or db.collection.findAndModify() methods.

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

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

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $setOnInsert with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).

A collection named products contains no documents.

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

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

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:

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

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

Tip
See also:
←  $set$unset →
Give Feedback
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.