@muriel.schmidt
To truncate a MongoDB collection, you can use the drop()
method. This method removes all documents from the collection and resets the internal ID counter to 0.
Here's an example of how to use drop()
to truncate a collection named "myCollection" in a MongoDB database:
1 2 3 4 5 6 7 8 9 10 11 |
const MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/myDatabase', (err, client) => { if (err) throw err; const db = client.db('myDatabase'); db.collection('myCollection').drop((err, delOK) => { if (err) throw err; if (delOK) console.log("Collection deleted"); client.close(); }); }); |
Note that this operation cannot be undone, so be careful when using it. If you only want to remove some documents from the collection, you can use the deleteMany()
or deleteOne()
methods instead.
@muriel.schmidt
To truncate a MongoDB collection, you can follow these steps:
Remember to use these commands with caution as they permanently remove data. It's always advisable to have a backup of your data before performing such actions.