Java Mongodb 简明教程
Java & MongoDB - Create Collection
若要删除数据库,可以使用 MongoDatabse.createCollection() 方法在数据库中创建集合。
To drop a databases, you can use MongoDatabse.createCollection() method to create a collection in the databases.
// Creating a Mongo client
MongoClient mongoClient = MongoClients.create();
// Connect the database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
Example
以下是创建集合的代码片段 −
Following is the code snippet to create a collection −
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://localhost:27017");
// Connect to database
MongoDatabase database = mongoClient.getDatabase("myDb");
// Create the collection
database.createCollection("sampleCollection");
System.out.println("Collection created.");
}
}
现在,我们按照以下步骤编译并运行上述程序。
Now, let’s compile and run the above program as shown below.
$javac Tester.java
$java Tester