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
importjava.util.List;importjava.util.Set;importcom.mongodb.DB;importcom.mongodb.DBCollection;importcom.mongodb.MongoClient;importcom.mongodb.client.MongoDatabase;classKW{@SuppressWarnings("deprecation")publicstaticvoidmain(String[]args){try{MongoClientmc=newMongoClient("localhost",27017);System.out.println("Connection Established Successfully");List<String>dbs=mc.getDatabaseNames();System.out.println("Databases "+dbs);DBdb=mc.getDB(dbs.get(0));Set<String>collections=db.getCollectionNames();System.out.println("Collections "+collections);MongoDatabasemd=mc.getDatabase("DB");md.createCollection("holders");System.out.println("\nCollection Created");db=mc.getDB("DB");DBCollectioncollection=db.getCollection("holders");System.out.println(collection.toString());mc.close();System.out.println("Connection Released Successfully");}catch(Exceptione){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" ]
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.