w3resource
MongoDB Tutorial

MongoDB Field Update Operator - $setOnInsert

Description

In MongoDB, the $setOnInsert operator is used to set values to fields during an upsert only, the update() operation performs an insert when using the upsert option with the update().

In MongoDB, the $setOnInsert operator only make a difference to update() operations with the upsert flag, that this operation exclusively performs an insert.

When the update() has the upsert flag and it performs an update, that means the $setOnInsert has no effect.

Syntax:

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

Parameters:

Name Description
query may be an expression or condion
field1 name of the column or field
value1 value to be assign or set for a field

Our database name is 'myinfo' and our collection name is "items1" and suppose the collection is empty.

Example of MongoDB $setOnInsert operator to insert a document

The following upsert operation performs an insert and applies the $setOnInsert to set the field description to item1 and op_stock to 100:

>db.items1.update({ _id: 1 },{ $setOnInsert: {"description":"item1", "op_stock": 100 } },{ upsert: true });

The above example will insert new document into the collection items1

To see the newly inserted document -

> db.items1.find().pretty();

N.B. find() method displays the documents in a non structured format but to display the results in a formatted way, the pretty() method can be used.

Output of the command:

{ "_id" : 1, "description" : "item1", "op_stock" : 100 }

Example of MongoDB $setOnInsert operator to update a document

The following update() with the upsert flag operation performs an update:

>db.items1.update({ _id: 1 },{ $setOnInsert: {"op_stock": 200,"description":"item2" },$set: {"purqty": 100}},{ upsert:  true });

Here in the above example the update() with upsert operation only performs an update, because the op_stock and description field already exists in the document, so, MongoDB ignores the $setOnInsert operation and only applies the $set operation.

To see the updated output -

> db.employee.find().pretty();

N.B. find() method displays the documents in a non structured format but to display the results in a formatted way, the pretty() method can be used.

Output of the command:

{ "_id" : 1, "description" : "item1", "op_stock" : 100, "purqty" : 100 }

Previous: $set
Next: $unset



New Content: Composer: Dependency manager for PHP, R Programming