Java Mongodb 简明教程
Java & MongoDB - Drop Collection
若要删除数据库,可以使用 collection.drop() 方法删除数据库中的集合。
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// delete the collection
collection.drop();
Example
以下是删除集合的代码片段 −
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Tester {
public static void main(String[] args) {
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// get the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
collection.drop();
System.out.println("Collection dropped.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
$javac Tester.java
$java Tester