$setOnInsert

Sets field values only when an upsert operation results in inserting a new document, having no effect when updating existing documents.

Syntax

{ $setOnInsert: { <field1>: <value1>, <field2>: <value2> } }

Parameters

fieldstringrequired

The name of the field to set only on insert (supports dot notation for nested fields)

valueobjectrequired

The value to assign to the field only when inserting a new document (any valid BSON type)

Examples

Basic setOnInsert usage

Set initialization fields only when creating new store records

Query:

db.stores.updateOne({ "_id": "new-store-001" }, { $set: { "name": "Electronics Store" }, $setOnInsert: { "createdDate": new Date(), "status": "new", "version": 1 } }, { upsert: true })

Output:

Creates new document with both $set and $setOnInsert fields, or updates existing with only $set fields

Initialize nested structures

Set complex nested objects only during document creation

Query:

db.stores.updateOne({ "name": "Gaming Paradise" }, { $set: { "location": { "city": "Seattle" } }, $setOnInsert: { "staff": { "totalStaff": { "fullTime": 5, "partTime": 8 } }, "sales": { "totalSales": 0 } } }, { upsert: true })

Output:

Initializes complex nested structures only when creating new documents

Set default arrays and objects

Initialize arrays and default values for new documents

Query:

db.stores.updateOne({ "city": "Portland" }, { $set: { "status": "active" }, $setOnInsert: { "categories": ["electronics", "gadgets"], "ratings": { "average": 0, "count": 0 }, "inventory": [] } }, { upsert: true })

Output:

Creates new document with default arrays and objects, or updates existing document without modifying these fields

Combine with multiple operators

Use setOnInsert alongside other update operators

Query:

db.stores.updateOne({ "_id": "multi-op-store" }, { $inc: { "sales.totalSales": 1000 }, $setOnInsert: { "establishedDate": new Date(), "initialSales": 1000 }, $currentDate: { "lastUpdated": true } }, { upsert: true })

Output:

Applies all operators for new documents, but only $inc and $currentDate for existing documents

Related