Skip to content

Updating Documents

Updating Documents

To update documents, the commands updateOne and updateMany can be used. The first command can be used to only find and update one document.

All the same parameters for finding a document to be updated can be used that were described above in the find section.

Setting Fields

For example to find a user with the username of user2 and to change that user's age to 65, we can use this $set operator to set fields to new values:

MongoDB
db.users.updateOne({ username: "test2" }, { $set: {
  age: 65
}})
Example Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Incrementing & Decrementing Values

We can also increment (or decrement by setting a negative number) fields by using the $inc operator:

MongoDB
db.users.updateOne({ username: "test2" }, { $inc: {
  age: 5
}})

Example Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Removing (Unsetting) Fields

Fields can be removed from a document by using the $unsetoperator:

MongoDB
db.users.updateOne({ username: "test2" }, {
  $unset: {
    password: ""
  }
})

Example Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Inserting Document If Not Exists

The additional upsert setting can be configured to automatically insert a document if it did not exist yet (false by default, so it will never create new a document if the editable document does not exist). It can be used like this:

MongoDB
db.users.updateOne({ username: "test3" }, {
  $set: {
    username: "test3",
    age: 62
  }
}, { upsert: true })
Example Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}

Combining Operators

We can combine the the operators freely, like below, where we set both the password and increment the age:

MongoDB
db.users.updateOne({ username: "test2" }, {
  $inc: {
    age: 5
  },
  $set: {
    password: "test123"
  }
})
Example Output
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}