MongoDB upsert() using findAndModify()

db.emp.findAndModify({
    query: { empnm: "mital" },
    update: { $set: { salary: 9000 } },
    upsert: true
})

Upsert means Update + Insert.

It performs two possible operations:

  1. If a matching document exists → it updates that document.
  2. If no matching document exists → it inserts a new document.

Explanation of each part

db.emp.findAndModify({

Performs a find-and-modify operation on the emp collection.

query: { empnm: "mital" }

Searches for an employee whose empnm is "mital".

update: { $set: { salary: 9000 } }

Sets the employee’s salary to 9000.

upsert: true

If "mital" is not found, MongoDB creates a new document.

Example 1: Employee already exists

Suppose collection contains:

{ empnm: "mital", salary: 7000 }

After executing the command:

db.emp.find()

Result:

{ empnm: "mital", salary: 9000 }

The existing document is updated.

Example 2: Employee does not exist

Suppose "mital" is not present.

The command:

db.emp.findAndModify({
    query: { empnm: "mital" },
    update: { $set: { salary: 9000 } },
    upsert: true
})

creates:

{
    empnm: "mital",
    salary: 9000
}

So, in simple words:

upsert: true = Update the document if it exists; otherwise, insert a new document.

Exam definition:
Upsert is a MongoDB operation that updates an existing document when a matching document is found, and inserts a new document when no matching document is found.

By admin