How to create a database in MongoDB using Java?



There is no separate method to create a MongoDB database in Java, you can create a database by invoking the getDatabase() method of the com.mongodb.MongoClient class.

Example

import com.mongodb.MongoClient;
public class CreatingDatabase {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      @SuppressWarnings("resource")
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Accessing the database
      mongo.getDatabase("myDatabase1");
      mongo.getDatabase("myDatabase2");
      mongo.getDatabase("myDatabase3");
      System.out.println("Databases created successfully");
   }
}

Output

Databases created successfully

Advertisements