Java & MongoDB - Create Collection



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

Output

On executing, the above program gives you the following output.

Collection created.
Advertisements