mongo remove all dbs
To remove all databases in MongoDB using the Go programming language, you can follow these steps:
- Import the necessary packages:
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
- Establish a connection to the MongoDB server:
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
// Handle connection error
}
defer client.Disconnect(context.Background())
- Access the admin database:
adminDB := client.Database("admin")
- List all databases:
databases, err := adminDB.ListDatabases(context.Background(), bson.M{})
if err != nil {
// Handle error
}
- Iterate over the list of databases and drop each one:
for _, db := range databases.Databases {
err := client.Database(db.Name).Drop(context.Background())
if err != nil {
// Handle error
}
}
This code first connects to the MongoDB server using the provided URI. It then accesses the admin database and retrieves a list of all databases. Finally, it iterates over the list and drops each database using the Drop
function.