By default, if no document matches the update query, the update() method does nothing.
However, by specifying upsert: true, the update() method either updates matching document or documents, or inserts a new document using the update specification if no matching document exists.
The following operation either updates a matching document by replacing it with a new document or adds a new document if no matching document exists.
> db.users.update(
... { Name : "Hymen Patel" },
... {
... "Name": "Himen Paatel",
... "Email": "email2himen@dotnet-funda.com",
... "Address1": "1257 Commons Drive",
... "City": "Cooperstown",
... "Zip Code": "13326",
... "Country": "USA"
... },
... { upsert: true }
... )
The update operation returns a WriteResult object which contains the status of the operation, including whether the db.collection.update() method modified an existing document or added a new document.
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("561324b1b6bb748311f00aac")
})
Specify upsert: true for the update specific fields operation
db.users.update(
{ Name : "Himen Patel" },
{$set :
{ "Email" : "admin@dotnet-fundamentals.com"} },
{upsert: true}
)