Skip to content

#12 Update & Delete Documents in MongoDB

MongoDB provides a wide range of methods for updating documents in collections, featuring update operators like $set, $pull, $inc, and $push, each with specific functions to modify data structures efficiently.

Update a Single Document

For example, I want to update Emily Brown working experience year from 6 to 7. We can use UpdateOne()

> db.personnel.updateOne({"name": "Emily Brown"},        # specify the condition
                         {$set:{"working_experience":7}}); # how to update
#before
db.personnel.find({"name":"Emily Brown"})
[
  {
    _id: ObjectId('66053f848ccb6407b4ba21c7'),
    name: 'Emily Brown',
    age: 32,
    working_experience: 6,
    department: 'Human Resources',
    salary: 62000,
    skills: [ 'Recruitment', 'Employee Relations', 'Training' ]
  }
]
#after
db.personnel.find({"name":"Emily Brown"})
[
  {
    _id: ObjectId('66053f848ccb6407b4ba21c7'),
    name: 'Emily Brown',
    age: 32,
    working_experience: 7,
    department: 'Human Resources',
    salary: 62000,
    skills: [ 'Recruitment', 'Employee Relations', 'Training' ]
  }
]

Update Multiple Documents

We also can update multiple documents at one time with UpdateMany(). It requires the exact filter condition. For example, I want to change the “Research and Development” department name to “R&D”.

> db.personnel.updateMany({"department": "Research and Development"}, 
                          {$set:{"department":"R&D"}});            
# check the result
 
> db.personnel.find({"department":"R&D"});
[
  {
    _id: ObjectId('66053f848ccb6407b4ba21cb'),
    name: 'Michelle Martinez',
    age: 31,
    working_experience: 5,
    department: 'R&D',
    salary: 63000,
    skills: [ 'Research', 'Data Analysis', 'Python', 'Machine Learning' ]
  },
  {
    _id: ObjectId('6606ab50877cee4bbbaf4c28'),
    name: 'Timi Mangos',
    age: 33,
    working_experience: 6,
    department: 'R&D',
    salary: 65000,
    skills: [
      'Research',
      'Data Analysis',
      'Python',
      'Machine Learning',
      'Database'
    ]
  }
]

Update with Increment

We also can update a numeric field by increment or decrement. For example, I want to add 1000 for employees whose salary is below 60000.

  • For increment, you can use $inc and assign positive number;
  • For decrement, you can use $inc and simply assign negative number. (e.g. -1000)
> db.personnel.updateMany({"salary": {"$lt": 60000}},  # specify the condition
                          {$inc:{"salary":1000}})      # how to update
#before
> db.personnel.find({ "salary": { $lt: 60000}},  { "name": 1, "salary": 1 })

[
  {
    _id: ObjectId('66053f848ccb6407b4ba21c5'),
    name: 'Jane Smith',
    salary: 55000
  },
  {
    _id: ObjectId('66053f848ccb6407b4ba21c9'),
    name: 'Sarah Lee',
    salary: 50000
  },
  {
    _id: ObjectId('66053f848ccb6407b4ba21cc'),
    name: 'Daniel Thompson',
    salary: 58000
  }
]
#after 
#before
> db.personnel.find({ "salary": { $lt: 60000}},  { "name": 1, "salary": 1 })
[
  {
    _id: ObjectId('66053f848ccb6407b4ba21c5'),
    name: 'Jane Smith',
    salary: 56000
  },
  {
    _id: ObjectId('66053f848ccb6407b4ba21c9'),
    name: 'Sarah Lee',
    salary: 51000
  },
  {
    _id: ObjectId('66053f848ccb6407b4ba21cc'),
    name: 'Daniel Thompson',
    salary: 59000
  }
]

Update element in an Array

Update in Array is a bit complicated than the above examples. We can add an element, delete an element or change an element in Array.

Add an element

As you can see from the examples above, the field skills is an Array, containing several different elements. For example, I want o add a skill called “NoSQL” to the employee Michelle Martinez.

For adding an element, you can use $push.

> db.personnel.updateOne(
   { "name": "Michelle Martinez" },                       # Filter
   { $push: { "skills": "NoSQL" } } );                    # Update

#Let's check the result
db.personnel.find({"name":"Michelle Martinez"})
[
  {
    _id: ObjectId('66053f848ccb6407b4ba21cb'),
    name: 'Michelle Martinez',
    age: 31,
    working_experience: 5,
    department: 'R&D',
    salary: 63000,
    skills: [
      'Research',
      'Data Analysis',
      'Python',
      'Machine Learning',
      'NoSQL'
    ]
  }
]


Change an element

For example, I want to change skills of Timi Mangos from “Database” to “MongoDB”

For changing an element, you can use $set.

> db.personnel.updateOne(
   { "name": "Timi Mangos", "skills": "Database" },   # Filter
   { $set: { "skills.$": "MongoDB" } } );             # Update

# check the result
db.personnel.find({"name":"Timi Mangos"},{ "skills":1})
[
  {
    _id: ObjectId('6606ab50877cee4bbbaf4c28'),
    skills: [
      'Research',
      'Data Analysis',
      'Python',
      'Machine Learning',
      'MongoDB'
    ]
  }
]

Delete an element

For example, I want to remove the “Research” skill form Timi Mangos.

For deleting an element, you can use $pull.

db.personnel.updateOne(
   { "name": "Timi Mangos" },                         # Filter
   { $pull: { "skills": "Research" } });              # Update

# check the result
db.personnel.find({"name":"Timi Mangos"},{ "skills":1})
[
  {
    _id: ObjectId('6606ab50877cee4bbbaf4c28'),
    skills: [ 'Data Analysis', 'Python', 'Machine Learning', 'MongoDB' ]
  }
]