Java 和 MongoDB - 刪除集合



要刪除資料庫,可以使用 collection.drop() 方法來刪除資料庫中的集合。

// Get the collection
MongoCollection<Document> collection = database.getCollection("sampleCollection");

// delete the collection
collection.drop();

舉例

以下是用於刪除集合的程式碼段 -

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://: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

輸出

在執行時,上述程式會給您以下輸出。

Collection dropped.
廣告
© . All rights reserved.