Mongoose: 3 Ways to Remove All Documents from a Collection

Updated: December 30, 2023 By: Guest Contributor Post a comment

When working with MongoDB through Mongoose, there are occasions where you might want to remove all the documents from a collection. This guide presents three solutions to accomplish this task, each with its own trade-offs.

Solution 1: Using deleteMany

The deleteMany method is a straightforward way to remove all documents from a collection. It’s a part of Mongoose’s query interface.

Steps:

  • Begin by opening your project editor and importing Mongoose.
  • Connect to your MongoDB database.
  • Use the Model.deleteMany method without any filter to match all documents.
  • Execute the operation and handle the promise.

Code example:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDB');

const YourModel = mongoose.model('YourModel', new mongoose.Schema({ /* schema */ }));

async function deleteAllDocuments() {
  const result = await YourModel.deleteMany({});
  console.log(result);
}

deleteAllDocuments();

Pros: Simple syntax, directly communicates intent.
Cons: Requires an active connection, not recommended for very large collections due to potential performance impact.

Solution 2: Using remove

The remove method is similar to deleteMany, but it’s now deprecated in favor of deleteMany. It is still used in older codebases or for backwards compatibility.

Steps:

  • Open your Node.js environment and ensure Mongoose is installed.
  • Connect with your database.
  • Invoke the remove method with an empty filter object on your model.
  • Handle the result of the promise.

Here’s a small example:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDB');

const YourModel = mongoose.model('YourModel', new mongoose.Schema({ /* schema */ }));

async function removeAllDocuments() {
  const result = await YourModel.remove({});
  console.log(result);
}

removeAllDocuments();

Pros: Familiar for those who have worked with older Mongoose versions.
Cons: Deprecated, may be removed in the future, which would require refactoring of codebase.

Solution 3: Drop the Collection

Dropping the collection entirely is a more drastic approach but effective for completely resetting a collection. It’s usually faster than deleteMany but also removes indexes and collection-specific metadata.

The boring steps:

  • Ensure you are in a Node.js environment with Mongoose installed.
  • Open a database connection.
  • Use the drop method associated with the native MongoDB connection object.
  • Catch any errors, especially the one that occurs if the collection doesn’t exist.

And here’s the exciting example:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDB');

const conn = mongoose.connection;

async function dropCollection() {
  try {
    await conn.collection('yourcollectionname').drop();
    console.log('Collection dropped');
  } catch (error) {
    if (error.code === 26) {
      console.log('Collection not found!');
    } else {
      console.error(error);
    }
  }
}

dropCollection();

Pros: Fast and efficient for complete resets, especially on very large collections.
Cons: Removes indexes and any collection-specific settings, the collection must be re-created manually afterwards.

Conclusion

Each method listed above serves to remove all documents from a Mongoose collection with distinct considerations. The choice between deleteMany, remove, and dropping the collection will depend on the specific requirements such as whether you need to maintain collection settings, the size of the collection, and the version of the Mongoose you are working with. These factors will guide you to select the most suitable approach for your task.