如何使用 Java 删除 MongoDB 中的数据库?

javaobject oriented programmingprogramming更新于 2025/10/7 22:04:17

MongoDB db.dropDatabase() 命令用于删除现有数据库。这将删除当前数据库。如果您未选择任何数据库,则将删除默认(测试)数据库。

语法

db.dropDatabase()

在 Java 中删除数据库时,首先使用 getDatabase() 方法获取所需数据库的对象,然后通过调用 drop() 方法将其删除。

示例

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class DropingDatabase {
   public static void main( String args[] ) {
      //创建 MongoDB 客户端
      @SuppressWarnings("resource")
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //创建数据库
      mongo.getDatabase("myDatabase");
      System.out.println("Databases created successfully");
      MongoDatabase database = mongo.getDatabase("myDatabase");
      database.drop();
   }
}

输出

Database deleted successfully

相关文章


有用资源