MongoDB update query example

Update specific fields of a single document

Instead of replacing the whole document it is mostly required to just modify one or some fields of a document and keep the other fields untouched. For this use case MongoDB provides different operators that can be specified in the update command.

Replace field values of a document using the $set operator

If only one field of a document should be updated the "$set" operator can be used. The set operator will override the old value of a specified field.

The following update command finds the first document which firstname field is equal "Max" and updates (sets) the lastname field to "Maier".

Maier".


db.customers.update(
>
 db.customers.update(
  {"firstname": "Max"},
  { 
    $set: {
      "lastname": "Maier"
    }
  }
);

To update multiple fields of a document the command looks like this:

> db.customers.update(
  {"firstname": "Max"},
  { 
    $set: {
      "lastname": "Maier",
      "email": "p.maier@example.com"
    }
  }
);

To update a field that is nested in the JSON structure the following command can be used:


>
 db.customers.update(
  {"firstname": "Max"},
  { 
    $set: {
      "lastname": "Maier",
      "address.street": "another street"
    }
  }
)
;

Update specific fields of multiple documents

So far all MongoDB update queries only updated/replaced exactly one document even though the selector matched multiple documents. To update all matching documents an addional option must be set:

> db.customers.update(
  {"firstname": "Max"},
  { 
    $set: {
      "email": "p.maier@example.com"
    }
  },
  {"multi": true}
);

This command returns the following result:

WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })

In this example nMatched shows that two documents have been found by the document selector query but nModified shows that only one document have been updated by the update command. nModified is smaller then nMatched in case the update command sets the fields of some document to its current values. In other words: when the update operation doesn't change any field of some documents.

 

RESOURCES:

 

Mongodb training in chennai

 

Mongodb official