Objective and Prerequisites

Objective: This segment introduces implementation of how to create a database and collection in MongoDB using Java.

Prerequisites: MongoDB setup is installed and running in the background. Also, the project has been developed and executed in Eclipse IDE (Integrated Development Environment).

To run the following program, you need to download the MongoDB Java driver jar file Download MongoDB Java driver. Once downloaded, you can import the library by right-clicking on your project in Eclipse -> Properties -> Java Build Path -> Libraries -> Add External JARs...

Start MongoDB (running mongo.exe)
MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.2.3

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

> use admin
switched to db admin

> db.getCollectionNames()
[ "system.version" ]
Java MongoDB to create database and collection
KW.java
import java.util.List;
import java.util.Set;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

class KW
{
    @SuppressWarnings("deprecation")
    public static void main(String[] args)
    {
        try
        {
            MongoClient mc = new MongoClient("localhost", 27017);
            System.out.println("Connection Established Successfully");
            
            List<String> dbs = mc.getDatabaseNames();
            System.out.println("Databases "+dbs);
            
            DB db = mc.getDB(dbs.get(0));
            Set<String> collections = db.getCollectionNames();
            System.out.println("Collections "+collections);
            
            MongoDatabase md = mc.getDatabase("DB");
            md.createCollection("holders");
            System.out.println("\nCollection Created");

            db = mc.getDB("DB");
            DBCollection collection = db.getCollection("holders");
            System.out.println(collection.toString());

            mc.close();
            System.out.println("Connection Released Successfully");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
Output
Connection Established Successfully
Databases [admin, config, local]
Collections [system.version]

Collection Created
DBCollection{database=DB{name='DB'}, name='holders'}
Connection Released Successfully
MongoDB Instance
> show dbs
DB      0.000GB
admin   0.000GB
config  0.000GB
local   0.000GB

> use DB
switched to db DB

> db.getCollectionNames()
[ "holders" ]
Advertisement