Java & MongoDB - 建立集合



若要刪除資料庫,可以使用 MongoDatabse.createCollection() 方法在資料庫中建立一個集合。

// Creating a Mongo client 
MongoClient mongoClient = MongoClients.create();

// Connect the database	   
MongoDatabase database = mongoClient.getDatabase("myDb");

// Create the collection
database.createCollection("sampleCollection");

示例

以下是建立集合的程式碼片段 -

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://:27017");

      // Connect to database
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Create the collection
      database.createCollection("sampleCollection");
      System.out.println("Collection created.");
   }
}

現在,讓我們像下面所示那樣編譯和執行上面的程式。

$javac Tester.java 
$java Tester

輸出

執行後,上面程式給你提供以下輸出。

Collection created.
廣告
© . All rights reserved.