$setOnInsert (Set on Insert)
Last updated: 2026-10-09
$setOnInsert (Set on Insert)
$setOnInsert sets field values only when an upsert inserts a new document; it is ignored when an existing document is matched. `{ $setOnInsert: { createdAt: new Date() } }`. Paired with upsert: true it records creation timestamps and initializes defaults — set-on-create, leave-on-update semantics.
| Category | Update Field |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $setOnInsert: { <field>: <value> } }
⚙️ Parameters
| field | The field set only on insert. |
|---|---|
| value | The initial value, e.g. a creation time. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $setOnInsert: createdAt set only on insert
db.users.updateOne(
{ email: 'alice@example.com' },
{
$set: { name: 'Alice' },
$setOnInsert: { createdAt: new Date() }
},
{ upsert: true }
)
Output:
// createdAt is recorded on first insert; later updates leave it alone
📌 Notes
- Applies only when the upsert inserts
- Use alongside $set so initialization and updates each do their job
- Great for immutable fields like createdAt
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhen does $setOnInsert take effect?
AOnly when the upsert actually inserts; ignored when updating an existing document.
QCan $setOnInsert and $set be used together?
AYes; $set applies every time, $setOnInsert only on insert.
QMust upsert: true be set?
AYes, otherwise it never fires in pure update scenarios.