Connect to MongoDB from Java using MongoDB Java Driver
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 this 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 this menu navigation path: 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.
MongoClient mongoClient = new MongoClient( host , port );
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.
mongoClient.close();
Example – Connection to MongoDB using Java
Following is an example Java Program to demonstrate on how to establish a connection to MongoDB by creating a MongoClient :
example.java
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
/**
* Created by TutorialKart on 31/10/17.
*/
public class JavaMongoConnectionExample {
public static void main(String[] args) {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "127.0.0.1" , 27017 );
System.out.println("Connected to MongoDB!");
} catch (MongoException e) {
e.printStackTrace();
} finally {
if(mongoClient!=null)
mongoClient.close();
}
}
}
Console Output
Nov 01, 2017 8:52:44 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connected to MongoDB!
References
Conclusion
In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Java Application using MongoDB Java Driver.