OPTIONS
翻译或纠错本页面

$setOnInsert

$setOnInsert

2.4 新版功能.

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 is ignored.

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 }
)

Example

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 }
)

The new document is created with _id equal to 1 from the <query> condition, and the $set and $setOnInsert operations are applied 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.

←   $rename $set  →
ON THIS PAGE