# How to delete documents in Mongoose

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 9, 2022. Topics: Node.js, Mongoose, MongoDB.
Canonical URL: https://attacomsian.com/blog/mongoose-delete-documents

> Learn how to delete documents from a MongoDB collection using Mongoose methods like deleteOne, deleteMany, findOneAndDelete, and findByIdAndDelete.

Mongoose provides 4 different ways to remove a document from a MongoDB collection. These methods include `deleteOne()`, `deleteMany()`, and `findOneAndDelete()`.

## `deleteMany()` method

The `deleteMany()` method removes all documents that match the given conditions from the MongoDB collection. It returns an object with the property `deletedCount` containing the number of documents deleted.

Here is an example that uses `deleteMany()` to delete documents from MongoDB:

```javascript
const mongoose = require('mongoose')
const { Schema } = mongoose

const Course = mongoose.model(
  'Course',
  new Schema({
    name: String
  })
)

await Course.create([
  { name: 'JavaScript 101' }, 
  { name: 'Node 101' }, 
  { name: 'Java 101' }
])

const res = await Course.deleteMany({ name: /java$/i })

res.deletedCount // Number of documents deleted
```

If an empty object is passed as a condition to `deleteMany()`, it will remove all documents in the collection:

```javascript
await Course.deleteMany({}) // Delete all documents
```

## `deleteOne()` method

The `deleteOne()` method works similar to `deleteMany()` except that it deletes the first document that matches the given conditions:

```javascript
await Course.deleteOne({ name: 'Node 101' })
```

## `findOneAndDelete()` method

The `findOneAndDelete()` method differs slightly from `deleteMany()` and `deleteOne()` in that it finds a matching document, delete it from the collection, and returns the found document back to the callback function.

Here is an example:

```javascript
const doc = await Course.findOneAndDelete({ name: 'Node 101' })

doc.name // Node 101
```

There is another variant of this method called `findByIdAndDelete()` that takes in the value of the `_id` field as input and remove the document from the collection:

```javascript
const id = '345XV'
const doc = await Course.findByIdAndDelete(id)
```

Under the hood, the `findByIdAndDelete(id)` method is a shorthand for `findOneAndDelete({  _id: id })`.
