Java JDBC Connect to MongoDB Database

In this tutorial, we will learn how to connect a Java application to a MongoDB database using the MongoDB Java driver. While MongoDB is a NoSQL database and doesn't use JDBC for connectivity, we will use the MongoDB Java driver to achieve the connection and perform basic CRUD operations.

Prerequisites

  • MongoDB server installed and running.
  • MongoDB Java driver added to your project.

Step-by-Step Guide

1. Set Up Dependencies

Ensure you have the MongoDB Java driver in your classpath. If you are using Maven, add the following dependency to your pom.xml:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.4.1</version>
</dependency>

2. Establish a Database Connection

First, we need to establish a connection to the MongoDB database using the MongoClients class.

3. Perform Basic CRUD Operations

We will perform Create, Read, Update, and Delete operations on a MongoDB collection.

Example Code

Below is the complete example code demonstrating how to connect to a MongoDB database and perform CRUD operations.

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import static com.mongodb.client.model.Filters.eq;

public class MongoDBExample {

    private static final String CONNECTION_STRING = "mongodb://localhost:27017";
    private static final String DATABASE_NAME = "testdb";
    private static final String COLLECTION_NAME = "books";

    public static void main(String[] args) {
        // Establish a connection to MongoDB
        try (MongoClient mongoClient = MongoClients.create(CONNECTION_STRING)) {
            // Access the database
            MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME);
            System.out.println("Connected to the database: " + DATABASE_NAME);

            // Access the collection
            MongoCollection<Document> collection = database.getCollection(COLLECTION_NAME);
            System.out.println("Connected to the collection: " + COLLECTION_NAME);

            // Perform CRUD operations
            // Create
            Document book1 = new Document("title", "Effective Java")
                    .append("author", "Joshua Bloch")
                    .append("year", 2008);
            collection.insertOne(book1);
            System.out.println("Inserted document: " + book1.toJson());

            // Read
            Document foundBook = collection.find(eq("title", "Effective Java")).first();
            if (foundBook != null) {
                System.out.println("Found document: " + foundBook.toJson());
            } else {
                System.out.println("Document not found");
            }

            // Update
            collection.updateOne(eq("title", "Effective Java"),
                    new Document("$set", new Document("year", 2018)));
            System.out.println("Updated document");

            // Delete
            collection.deleteOne(eq("title", "Effective Java"));
            System.out.println("Deleted document");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation

  1. MongoDB Connection:

    • MongoClients.create(CONNECTION_STRING) is used to establish a connection to the MongoDB server.
    • Replace CONNECTION_STRING with your actual MongoDB connection string.
  2. Access the Database and Collection:

    • mongoClient.getDatabase(DATABASE_NAME) accesses the database named testdb.
    • database.getCollection(COLLECTION_NAME) accesses the collection named books.
  3. CRUD Operations:

    • Create: Insert a new document into the collection using collection.insertOne().
    • Read: Retrieve a document from the collection using collection.find().first().
    • Update: Update a document in the collection using collection.updateOne().
    • Delete: Delete a document from the collection using collection.deleteOne().

Output

Running the code will produce output similar to the following:

Connected to the database: testdb
Connected to the collection: books
Inserted document: {"title": "Effective Java", "author": "Joshua Bloch", "year": 2008}
Found document: {"title": "Effective Java", "author": "Joshua Bloch", "year": 2008}
Updated document
Deleted document

Conclusion

The MongoDB Java driver allows a Java application to connect to a MongoDB database. This tutorial demonstrated how to establish a connection and perform basic CRUD operations on a MongoDB collection. This approach can be adapted for more complex operations and use cases.

Comments