How to delete documents in Mongoose

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.