Create Collection in MongoDB using Java
In this example, We will show you the simple program about, How to create collection in MongoDB using Java. The example java program has been tested with environment (mongodb server 3.4.2) and output shared in the same post.
Note: In order to connect to MongoDB using java, We have to download the java driver for the mongodb, Which you can find it in the maven repository.
Download the MongoDB Java Driver from Maven Repository, In this example we are using mongodb-java-driver version 3.4.2
Getting the Connection
In order to create the collection, First you have to get the connection of mongodb, To get that we have to create an object for MongoClient by passing host name (ie: localhost) and port (ie: 27017 is default port number) number as a parameter.
MongoClient client = new MongoClient("localhost", 27017);
Choosing the Database
Once you have connected to mongodb server, then you have to select the database where you want to create the collection. In this case my database name is “dineshkrish“, you can select it accordingly based on the database name.
MongoDatabase database = client.getDatabase("dineshkrish");
Creating the Collection
The collection can be created by invoking the following line.
database.createCollection("employee");
Complete Example
Finally, We can able to create collection in Mongodb using Java through below code snippet.
package com.dineshkrish.mongo; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; /** * * @author Dinesh Krishnan * */ public class CreateCollection { public static void main(String[] args) { // getting mongodb connection using host name 'localhost' and port '27017' MongoClient client = new MongoClient("localhost", 27017); // choosing the database ie: 'dineshkrish' MongoDatabase database = client.getDatabase("dineshkrish"); // creating the collection called 'employee' database.createCollection("employee"); // closing the connection client.close(); } }
Run it
To see the output, open the mongodb terminal -> select the database by typing use database-name -> list the collection by typing show collections, then you should be able to see the output, which is attached below screen shot.
References
1. MongoDB Java API Documentation
2. JavaDoc – MongoClient Class
3. JavaDoc – MongoDatabase Interface
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet