Connect to MongoDB from Java

Connect to MongoDB from Java – In this MongoDB Tutorial, we shall learn to connect to MongoDB from Java Application.

To connect to MongoDB from Java Application, follow the below step by step guide :

  1. Download MongoDB Java Driver

    Download latest available MongoDB Java Driver from Maven Repository.
    https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/
    For this tutorial, we shall download 3.5.0, which was then latest.

  2. Add jar file to the build path.

    In IntelliJ IDEA, copy the jar file to lib folder, then right click on the jar file and ‘Add as Library’.
    In Eclipse, follow : Project -> Properties -> Java Build Path -> Libraries -> Add Jars -> Select the jar -> Click “Apply” -> Click “OK”

  3. Create MongoClient

    In your Java Program, create a new MongoClient with host and port provided as arguments to the constructor.

    host (String) and port (Integer) are IP Address or hostname and Port Number respectively at which MongoDB Daemon Service is running.
    With the details provided, mongoClient creates a new Client to the MongoDB.

  4. MongoClient is Ready

    If there is no exception thrown during MongoClient creation, your MongoClient is successfully connected to MongoDB.

  5. Close connection to MongoDB

    Once you are done with the MongoDB Operations, close the connection between MongoClient and MongoDB Daemon Service.

 

Example Java Program – To demonstrate Connection to MongoDB

Following is an example Java Program to demonstrate on how to establish a connection to MongoDB by creating a MongoClient :

 

References

  1. Java Programming Tutorial

Conclusion :

In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Java Application using MongoDB Java Driver.