mongodb 在Mongo Db中清除多个集合

frebpwbc  于 2023-06-29  发布在  Go
关注(0)|答案(2)|浏览(117)

我想一次性从MongoDB中删除20个集合。有没有什么方法或通过脚本来删除它们?

72qzrwbm

72qzrwbm1#

您可以迭代集合并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();
im9ewurl

im9ewurl2#

要删除集合,可以使用DropCollectionAsync方法。
下面是一个示例代码,用于删除由名称数组定义的多个集合:

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);
}

相关问题