How to create a MongoDB collection using Java?

JavaObject Oriented ProgrammingProgramming

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

Syntax

db.createCollection(name, options)

Where

  • 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.

Example

> 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.

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.2</version>
</dependency>
  • 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).

Example

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");
   }
}

Output

Collection created successfully
raja
Published on 10-Apr-2020 11:41:11
Advertisements