What You Will Learn:
- How to add the MongoDB Java driver to your project.
- Write a Java program to connect to a MongoDB database.
- Test the connection to MongoDB by running the program.
Technologies Used:
- JDK: Version 1.8 or later (Recommended: Latest version)
- MongoDB: Version 6.0 or later
- MongoDB Java Driver: Version 5.1.4 (latest)
Step 1: Add MongoDB Java Driver Dependency
To connect to MongoDB, you need to add the MongoDB Java Driver to your project.
For Maven Users:
Add the following dependency to your pom.xml
file:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.1.4</version>
</dependency>
For Gradle Users:
Add the following line to your build.gradle
file:
implementation 'org.mongodb:mongodb-driver-sync:5.1.4'
If you don't use Maven or Gradle, you can download the MongoDB Java Driver JAR file from the official website and add it to your project manually.
Step 2: Connect to MongoDB
Make sure that MongoDB is installed and running on your machine. MongoDB usually runs on port 27017
. By default, the connection string to MongoDB looks like this:
mongodb://localhost:27017
This connection string connects to a local MongoDB server running on your computer.
Creating a Database in MongoDB:
You don’t need to manually create a database in MongoDB. When you insert data into a collection in MongoDB, it automatically creates the database if it doesn’t exist.
Step 3: Write Java Code to Connect to MongoDB
Here’s a simple Java program that connects to MongoDB and inserts a document into a collection.
Code Example:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDBConnectionExample {
// MongoDB connection URI
private static final String URI = "mongodb://localhost:27017";
public static void main(String[] args) {
// Step 1: Create a MongoClient instance to connect to MongoDB
try (MongoClient mongoClient = MongoClients.create(URI)) {
// Step 2: Access the database (it will create it if it doesn't exist)
MongoDatabase database = mongoClient.getDatabase("mydb");
// Step 3: Confirm the connection
System.out.println("Connected to the database: " + database.getName());
// Step 4: Insert a document into a collection
database.getCollection("testCollection")
.insertOne(new Document("name", "Raj").append("age", 30));
// Step 5: Confirm document insertion
System.out.println("Inserted a document into the testCollection.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
Step 1: We use
MongoClients.create()
to establish a connection to the MongoDB server. The connection URImongodb://localhost:27017
tells MongoDB to connect to the server running locally on port27017
.Step 2:
getDatabase("mydb")
is used to access themydb
database. If the database does not exist, MongoDB will create it when we insert data.Step 3: The program prints the name of the connected database to confirm that the connection was successful.
Step 4: We insert a new document into the
testCollection
collection. MongoDB will automatically create this collection if it doesn’t exist. The document contains two fields:name
andage
.Step 5: The program confirms that the document has been inserted.
Step 4: Run the Java Program
After writing the code, run the program. If everything is set up correctly, you will see the following output:
Connected to the database: mydb
Inserted a document into the testCollection.
You'll see an error message if there’s an issue, such as MongoDB not running or an incorrect connection string.
Conclusion
In this tutorial, you learned how to:
- Add the MongoDB Java Driver to your project.
- Write Java code to connect to MongoDB.
- Insert a document into a MongoDB collection.
This simple example can be expanded to include more operations, such as updating or deleting documents or querying collections. MongoDB and Java together offer powerful tools for building scalable applications.
Comments
Post a Comment
Leave Comment