The deleteMany() Function in Mongoose

Nov 5, 2021

The deleteMany() function is how you can delete multiple documents from a collection using Mongoose. It takes up to two parameters:

  1. condition, what a document should contain to be eligible for deletion. You can omit this property to delete all documents in the model.
  2. options, other configurable parameters, like session or writeConcern.
const testSchema = new mongoose.Schema({
    name: String
});
const Test = mongoose.model('Test', testSchema);

await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Masteringjs'});
await Test.create({name: 'MeanIT'});

await Test.deleteMany({name: 'Test Testerson'});
await Test.find(); // will return Masteringjs and MeanIT documents

Return Value

Once the documents are deleted, it will return an object with a property, deletedCount, containing the number of documents deleted.

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

await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Test Testerson'});
await Test.create({name: 'Masteringjs'});
await Test.create({name: 'MeanIT'});

await Test.deleteMany({name: 'Test Testerson'}); // {deletedCount: 3}

Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need to know to build production-ready full-stack apps with Node.js and MongoDB in a few days. Get your copy!

More Mongoose Tutorials