Java Mongodb 简明教程
Java & MongoDB - Drop Database
若要删除数据库,可以使用 MongoDatabse.drop() 方法来删除选定的数据库。
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create();
// connect the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// drop the database
database.drop();
Example
以下是删除数据库的代码片段 −
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("myDb");
// drop the database
database.drop();
System.out.println("Database dropped.");
// print the databases
MongoIterable<String> list = mongoClient.listDatabaseNames();
for (String name : list) {
System.out.println(name);
}
}
}
现在,我们按照以下步骤编译并运行上述程序。
$javac Tester.java
$java Tester