querydrill

Learn ›MongoDB fundamentals ›Updating documents

update() and $set

update$set

Updates are where MongoDB will genuinely destroy your data if you get the syntax slightly wrong. The rule is short: without an update operator, you are not editing a document, you are replacing it.

Suppose:

{
  _id: 101,
  name: "Denish",
  age: 21,
  skills: ["Node.js", "Kafka"]
}

$set

db.users.updateOne(
  { _id: 101 },
  {
    $set: {
      age: 29
    }
  }
)

⚠️ Dangerous mistake

Suppose:

address: {
  city: "Surat",
  country: "India"
}

You do:

$set: {
  address: {
    city: "Bangalore"
  }
}

Result:

address: {
  city: "Bangalore"
}

You replaced the entire object.

If you want only the city:

$set: {
  "address.city": "Bangalore"
}

Result:

address: {
  city: "Bangalore",
  country: "India"
}

Again: dot notation matters.

Practise this

1 exercise