Course

Deleting Documents

Deleting Documents

In this lesson, we will learn how to delete documents from a collection in MongoDB using Mongoose.

Deleting a Single Document

To delete a single document from a collection, we can use the method. This method takes a filter object as an argument and deletes the first document that matches the filter.

Here's an example:

//
const result = await User.deleteOne({ name: "Alice" });
console.log(result);
//
{
  deletedCount: 1;
}

In this example, we are deleting the first document in the User collection that has the name Alice.

The method returns an object with a deletedCount property that indicates the number of documents deleted.

For the argument to , we can use any valid query filter object that we would use with the method. This allows us to target specific documents for deletion.

Deleting Multiple Documents

To delete multiple documents from a collection, we can use the method. This method takes a filter object as an argument and deletes all documents that match the filter.

Here's an example:

//
const result = await User.deleteMany({ age: { $lt: 30 } });
console.log(result);
//
{
  deletedCount: 2;
}

In this example, we are deleting all documents in the User collection where the age is less than 30.

The method returns an object with a deletedCount property that indicates the number of documents deleted.

Just like with , we can use any valid query filter object with to target specific documents for deletion.

As you can see, that includes operators like $lt (less than), $gt (greater than), $eq (equal to), and many others.

Deleting All Documents

To delete all documents from a collection, we can use the method with an empty filter object {}.

Here's an example:

//
const result = await User.deleteMany({});
console.log(result);
//
{
  deletedCount: 3;
}

In this example, we are deleting all documents in the User collection.

The method returns an object with a deletedCount property that indicates the number of documents deleted.

Conclusion

In this lesson, we learned how to delete documents from a collection in MongoDB using Mongoose. We covered deleting a single document with , deleting multiple documents with , and deleting all documents with and an empty filter object.

That concludes all of our CRUD operations in MongoDB using Mongoose. We have learned how to create, read, update, and delete documents in a collection. These operations are the foundation of working with MongoDB and Mongoose, and you will use them frequently in your applications.

In the next lesson, we will cover a more advanced topic: referencing.

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Relationships and Referencing Models in Mongoose