skip to Main Content

I want to delete 20 collection from MongoDB all in one go. Is there any way or through scripts to delete them all?

2

Answers


  1. To delete a collection, you can use the DropCollectionAsync method.

    Here is a sample code for dropping multiple collections defined by an array of names:

    var client = new MongoClient(connectionString);
    var database = client.GetDatabase(databaseName);
    var collectionNames = new List<string> { "collection1", "collection2" };
    
    foreach (var collectionName in collectionNames)
    {
        await database.DropCollectionAsync(collectionName);
    }
    
    Login or Signup to reply.
  2. You may iterate collections and drop()

        const MongoClient = require("mongodb").MongoClient;
    
        async function deleteCollections() {
          const uri = "mongodb://localhost:27017/mydb";
          const client = new MongoClient(uri);
          await client.connect();
          const database = client.db("mydb");
          const collections = ["collection1", "collection2", ..., 
          "collection20"];
          for (const collection of collections) {
             await database.collection(collection).drop();
          }
          await client.close();
        }
       deleteCollections();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search