如何使用Java建立MongoDB集合?
您可以使用**db.createCollection()**方法在MongoDB中建立集合。
語法
db.createCollection(name, options)
其中
**db** 是資料庫。
name 是您想要建立的集合的名稱。
Option 是一組可選引數,例如capped,auto indexed,size 和 max。
示例
> use myDatabase
switched to db myDatabase
> db.createCollection("myCollection")
{ "ok" : 1 }使用Java程式
在Java中,您可以使用**com.mongodb.client.MongoDatabase**介面的**createCollection()**方法建立集合。此方法接受一個字串值,表示集合的名稱。
因此,要使用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()**連線到資料庫。
透過傳遞集合的名稱(字串)來呼叫**createCollection()**方法。
示例
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
public class CreatingCollection {
public static void main( String args[] ) {
//Creating a MongoDB client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("myDatabase");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}輸出
Collection created successfully
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP