如何使用 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

更新於:2020年4月10日

2K+ 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.