Connecting to MongoDB from Java

To connect to MongoDB from Java, you need MongoDB Java driver. Depending on the type of project you are working on there are 3 ways to use this driver. If you are using Gradle or Maven, you can add it as a dependency. If you are not using a build system, you can use the legacy fat jar of the MongoDB Java driver.

Use the Gradle dependency,

dependencies {
    compile 'org.mongodb:mongodb-driver:3.4.2'
}

Or use the Maven dependency,

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.4.2</version>
    </dependency>
</dependencies>

Or use the MongoDB library jar file directly. This jar contains all the dependencies including the BSON library.

Note that the above example use version 3.4.2 of the MongoDB driver. You may want to use a later version if available.

Connecting to MongoDB from Java

The following program shows how to connect to MongoDB from Java. Note the use of a singleton pattern for MongoClient where the instance is loaded lazily. MongoClient is designed for multi-threaded calls and has a connection pool internally (default pool size in Java is 100). Hence for most use cases you will need just one instance of MongoClient. Using multiple MongoClient instances may lead to too many open connections in MongoDB.

The following example inserts and queries records in a collection named "user" in the "test" database. We also assume that the MongoDB is running on the local machine with default port.

import org.bson.Document;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

// Demo program for connecting to MongoDB.
// Uses singleton pattern for MongoClient.
public class MongoDemo {

    private static MongoClient mClient;

    // Singleton for MongoClient
    // Creates a single connection pool internally
    private MongoClient getMongoClient() {
        if (mClient == null) {
            mClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
        }
        return mClient;
    }

    // Utility method to get database instance
    private MongoDatabase getDB() {
        return getMongoClient().getDatabase("test");
    }

    // Utility method to get user collection
    private MongoCollection<Document> getUserCollection() {
        return getDB().getCollection("user");
    }

    public static void main(String[] args) {
        MongoDemo demo = new MongoDemo();
        demo.insertUser();
        demo.queryUsers();
    }

    // Read all documents from user collection
    private void queryUsers() {
        getUserCollection().find().forEach(new Block<Document>() {
            @Override
            public void apply(Document t) {
                System.out.println(t);
            }
        });
    }

    // Insert a document in user collection
    private void insertUser() {
        Document document = new Document("username","qpt")
                            .append("email", "testemail@example.com");
        getUserCollection().insertOne(document);
    }
}

We have used an iterator with a lambda function for reading Mongo documents. Alternatively you can use the DBCursor class to iterate through the document collection.

MongoDB Java References

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply