如何使用 Java 删除 MongoDB 集合?
javaobject oriented programmingprogramming更新于 2025/10/8 8:12:17
您可以使用 drop() 方法从 MongoDB 中删除现有集合。
语法
db.coll.drop()
其中,
db 是数据库。
coll 是您要插入文档的集合(名称)
示例
假设我们在 MongoDB 数据库中创建了 3 个集合,如下所示 −
> use sampleDatabase
switched to db sampleDatabase
> db.createCollection("students")
{ "ok" : 1 }
> db.createCollection("teachers")
{ "ok" : 1 }
> db.createCollection("sample")
{ "ok" : 1 }
> show collections
sample
students
teachers
以下查询删除名为 sample 的集合。
> db.sample.drop() true > show collections example students teachers
使用 Java 程序
在 Java 中,您可以使用 com.mongodb.client.MongoCollection 接口的 drop() 方法在当前集合中删除集合。
因此,要使用 Java 程序在 MongoDB 中删除集合 −
确保您已在系统中安装了 MongoDB
将以下依赖项添加到 Java 项目的 pom.xml 文件中。
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency>
通过实例化 MongoClient 类来创建 MongoDB 客户端。
使用 getDatabase() 方法连接到数据库。
使用 getCollection() 方法获取要删除的集合的对象。
通过调用 drop() 方法删除集合。
示例
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.MongoClient;
public class DropingCollection {
public static void main( String args[] ) {
//创建 Mongo 客户端
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//连接数据库
MongoDatabase database = mongo.getDatabase("mydatabase");
//创建多个集合
database.createCollection("sampleCollection1");
database.createCollection("sampleCollection2");
database.createCollection("sampleCollection3");
database.createCollection("sampleCollection4");
//检索集合列表
MongoIterable<String> list = database.listCollectionNames();
System.out.println("List of collections:");
for (String name : list) {
System.out.println(name);
}
database.getCollection("sampleCollection4").drop();
System.out.println("Collection dropped successfully");
System.out.println("List of collections after the delete operation:");
for (String name : list) {
System.out.println(name);
}
}
}
输出
List of collections: sampleCollection4 sampleCollection1 sampleCollection3 sampleCollection2 Collection dropped successfully List of collections after the delete operation: sampleCollection1 sampleCollection3 sampleCollection2
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

