MongoDB: How to truncate/empty a collection

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

MongoDB, a powerful NoSQL database, offers various operations to manage your data efficiently. Sometimes, you might need to truncate or empty a collection either for maintenance, resetting datasets during testing, or preparing the database for fresh data. In this tutorial, we will walk through how to truncate a collection in MongoDB with code examples demonstrating basic to advanced techniques, complemented with outputs where applicable.

Understanding Trunctate

In MongoDB, truncating a collection means removing all documents from the collection without deleting the collection itself. This operation is useful when you want to retain the indexes, validation rules, and other collection settings. Now, let’s get started with the simplest method to truncate a collection.

Using deleteMany

db.collection.deleteMany({})

This command will remove all documents in a collection but keep the collection itself and its indexes intact. Let’s see this in action with a sample collection named ‘users’.

db.users.deleteMany({})
// Output
{ "acknowledged" : true, "deletedCount" : 0 }

If the ‘users’ collection had any documents, the ‘deletedCount’ would indicate the number of documents removed.

Using drop() Method

Alternatively, the drop() method can be used to empty a collection. While this deletes the collection entirely and with it, indexes and options, use this with caution and only if you intend to recreate the collection from scratch.

db.users.drop()
// Output
true

Advanced Truncation Techniques

For more advanced use-cases, such as truncating multiple collections or incorporating error handling, you can use JavaScript script with MongoDB’s shell or drivers.

Truncating Multiple Collections

MongoDB: How to truncate/empty a collection /* Truncate multiple collections */
var collections = ['users', 'orders', 'products'];
collections.forEach(function(collName) {
  db[collName].deleteMany({});
});

This will iterate over the array of collection names and truncate each one. To ensure the commands are executed, checking the acknowledge property of the result can be added.

Bulk Write Operations

For handling bulk data and ensuring atomic operations while truncating, MongoDB offers bulk write operations:

const bulk = db.users.initializeUnorderedBulkOp();
bulk.find({}).remove();
bulk.execute();

The bulk.find({}).remove() tells MongoDB to queue up the removal of all documents without any filter, while bulk.execute() runs all bulk operations.

Error Handling and Transactional Truncation

MongoDB supports transactions which can be used to perform multiple deletion operations transactionally, ensuring that either all truncations are successful, or in the case of an error, none are applied.

MongoDB: How to truncate/empty a collection /* Start a session and a transaction */
const session = db.getMongo().startSession();
session.startTransaction();
try {
  session.getDatabase('yourdbname').users.deleteMany({}, { session });
  // Add more operations if needed
  session.commitTransaction();
} catch(e) {
  print('An error occurred during the transaction:', e);
  session.abortTransaction();
} finally {
  session.endSession();
}

Conclusion

To sum up, truncating a collection in MongoDB can be done efficiently using the deleteMany method or, when starting afresh, the drop method. Advanced techniques involve scripting to handle multiple collections, leveraging bulk writes for atomic operations, and using transactions for rollback capabilities on encountering errors. It’s vital to use these commands with caution and always ensure that you have current data backups before performing such operations.