Updating & Deleting Documents

Lesson 7
Author : Afrixi
Last Updated : February, 2023
MongoDB - noSQL Database
This course covers the basics of working with MongoDB.

Updating and deleting documents in MongoDB is a crucial aspect of working with the database. In this section, we will learn how to update and delete documents in MongoDB using the updateOne(), updateMany(), deleteOne(), and deleteMany() methods.

Updating Documents

The updateOne() method updates a single document that matches a specified filter. The method takes two arguments: a filter object to match the document to update, and an update object that specifies the changes to make. Here’s an example:

db.collection('users').updateOne(
   { name: 'John' },
   { $set: { age: 35 } }
);

This code will update the first document in the users collection where the name property is equal to 'John', and set the age property to 35.

The updateMany() method is similar to updateOne(), but updates all documents that match the specified filter. Here’s an example:

db.collection('users').updateMany(
   { status: 'Active' },
   { $set: { status: 'Inactive' } }
);

This code will update all documents in the users collection where the status property is equal to ‘Active’, and set the status property to ‘Inactive’.

Deleting Documents

The deleteOne() method deletes a single document that matches a specified filter. The method takes a filter object as an argument. Here’s an example:

db.collection('users').deleteOne({ name: 'John' });

This code will delete the first document in the users collection where the name property is equal to 'John'.

The deleteMany() method is similar to deleteOne(), but deletes all documents that match the specified filter. Here’s an example:

db.collection('users').deleteMany({ status: 'Inactive' });

This code will delete all documents in the users collection where the status property is equal to 'Inactive'.

It’s important to note that these methods are irreversible, so it’s always a good practice to take a backup of your database before performing any updates or deletions.