Sling Academy
Home/Node.js/Mongoose: 3 Ways to Remove All Documents from a Collection

Mongoose: 3 Ways to Remove All Documents from a Collection

Last updated: December 30, 2023

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.

Next Article: Mongoose: Find Documents That Contain a Given Value

Previous Article: Mongoose: $lt and $gt operators (with examples)

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates