How do I truncate a collection in MongoDB or is there such a thing?
Right now I have to delete 6 large collections all at once and I'm stopping the server, deleting the database files and then recreating the database and the collections in it. Is there a way to delete the data and leave the collection as it is? The delete operation takes very long time. I have millions of entries in the collections.
To truncate a collection and keep the indexes use
db.<collection>.remove({})
You can efficiently drop all data and indexes for a collection with db.collection.drop()
. Dropping a collection with a large number of documents and/or indexes will be significantly more efficient than deleting all documents using db.collection.remove({})
. The remove()
method does the extra housekeeping of updating indexes as documents are deleted, and would be even slower in a replica set environment where the oplog would include entries for each document removed rather than a single collection drop command.
Example using the mongo
shell:
var dbName = 'nukeme'; db.getSiblingDB(dbName).getCollectionNames().forEach(function(collName) { // Drop all collections except system ones (indexes/profile) if (!collName.startsWith("system.")) { // Safety hat print("WARNING: going to drop ["+dbName+"."+collName+"] in 5s .. hit Ctrl-C if you've changed your mind!"); sleep(5000); db[collName].drop(); } })
It is worth noting that dropping a collection has different outcomes on storage usage depending on the configured storage engine:
If you are instead dropping the database, you generally don't need to explicitly create the collections as they will be created as documents are inserted.
However, here is an example of dropping and recreating the database with the same collection names in the mongo
shell:
var dbName = 'nukeme'; // Save the old collection names before dropping the DB var oldNames = db.getSiblingDB(dbName).getCollectionNames(); // Safety hat print("WARNING: going to drop ["+dbName+"] in 5s .. hit Ctrl-C if you've changed your mind!") sleep(5000) db.getSiblingDB(dbName).dropDatabase(); // Recreate database with the same collection names oldNames.forEach(function(collName) { db.getSiblingDB(dbName).createCollection(collName); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With