如何使用 Java 删除 MongoDB 集合?
您可以使用 **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[] ) {
//Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("mydatabase");
//Creating multiple collections
database.createCollection("sampleCollection1");
database.createCollection("sampleCollection2");
database.createCollection("sampleCollection3");
database.createCollection("sampleCollection4");
//Retrieving the list of collections
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP