英文:
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<string> { "collection1", "collection2" };
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("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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论