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:

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:

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:

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:

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:

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

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

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.