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