Java Mongodb 简明教程
Java & MongoDB - Drop Collection
若要删除数据库,可以使用 collection.drop() 方法删除数据库中的集合。
To drop a databases, you can use collection.drop() method to drop a collection in the databases.
// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// delete the collection
collection.drop();
Example
以下是删除集合的代码片段 −
Following is the code snippet to drop a collection −
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.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester