How to create a MongoDB collection using Java?

You can create a collection in MongoDB using the db.createCollection() method.


db.createCollection(name, options)


  • db is the database.

  • name is the name of the collection you want to create.

  • Option is the set of optional parameters such as capped, auto indexed, size and, max.


> use myDatabase
switched to db myDatabase
> db.createCollection("myCollection")
{ "ok" : 1 }

Using Java program

In Java, you can create a collection using the createCollection() method of the com.mongodb.client.MongoDatabase interface. This method accepts a string value representing the name of the collection.

Therefore to create a collection in MongoDB using Java program −

  • Make sure you have installed MongoDB in your system

  • Add the following dependency to its pom.xml file of your Java project.

  • Create a MongoDB client by instantiating the MongoClient class.

  • Connect to a database using the getDatabase().

  • Invoke the createCollection() method by passing the name of the collection(string).


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
      System.out.println("Collection created successfully");


Collection created successfully