How to truncate mongodb collection?

by muriel.schmidt , in category: PHP Databases , 2 years ago

How to truncate mongodb collection?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brandy , 2 years ago

@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.

by cortez.connelly , a year ago

@muriel.schmidt 

To truncate a MongoDB collection, you can follow these steps:

  1. Connect to your MongoDB database using a MongoDB client, such as the MongoDB shell or MongoDB Compass.
  2. Select the database that contains the collection you want to truncate. use your_database_name
  3. To truncate the collection, you can either use the drop() method or deleteMany() method. The drop() method removes the entire collection, including all its indexes. db.your_collection_name.drop() The deleteMany() method deletes all documents in the collection, leaving behind an empty collection with the same name. db.your_collection_name.deleteMany({}) Note: If you want to delete only specific documents matching certain criteria, you can pass a filter as a parameter to the deleteMany() method.
  4. After executing the above command, the collection will be truncated, and all its documents will be deleted.


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.