清除Mongo Db中的多个集合

huangapple go评论60阅读模式
英文:

Clear multiple collection in Mongo Db

问题

我想一次性从MongoDB中删除20个集合。是否有任何方式或通过脚本来删除它们?

英文:

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

答案1

得分: 0

要删除集合,您可以使用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);
}
英文:

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&lt;string&gt; { &quot;collection1&quot;, &quot;collection2&quot; };

foreach (var collectionName in collectionNames)
{
    await database.DropCollectionAsync(collectionName);
}


</details>



# 答案2
**得分**: 0

以下是翻译好的部分:

```javascript
你可以迭代集合并使用 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();
英文:

You may iterate collections and drop()

    const MongoClient = require(&quot;mongodb&quot;).MongoClient;

    async function deleteCollections() {
      const uri = &quot;mongodb://localhost:27017/mydb&quot;;
      const client = new MongoClient(uri);
      await client.connect();
      const database = client.db(&quot;mydb&quot;);
      const collections = [&quot;collection1&quot;, &quot;collection2&quot;, ..., 
      &quot;collection20&quot;];
      for (const collection of collections) {
         await database.collection(collection).drop();
      }
      await client.close();
    }
   deleteCollections();

huangapple
  • 本文由 发表于 2023年6月9日 13:59:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定