Databases 7 min read

How to Build a Reusable MongoDB Utility Class in Java

This article presents a Java MongoDB utility comprising a static helper class and a MongoObject wrapper, explains methods for server and credential handling, client creation, collection access, and demonstrates usage with a sample main program and its output.

FunTester
FunTester
FunTester
How to Build a Reusable MongoDB Utility Class in Java

MongoBase utility class

The MongoBase class provides a set of static helper methods for building MongoDB connections without external frameworks. It abstracts the creation of ServerAddress, MongoCredential, MongoClient, MongoDatabase, and MongoCollection objects, and also supplies a method to close the client.

package com.fun.mongodb;
import com.fun.frame.SourceCode;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
import java.util.List;

public class MongoBase extends SourceCode {
    public static List<ServerAddress> getServers(ServerAddress... addresses) {
        return Arrays.asList(addresses);
    }
    public static ServerAddress getServerAdress(String host, int port) {
        return new ServerAddress(host, port);
    }
    public static List<MongoCredential> getCredentials(MongoCredential... credentials) {
        return Arrays.asList(credentials);
    }
    public static MongoCredential getMongoCredential(String userName, String database, String password) {
        return MongoCredential.createCredential(userName, database, password.toCharArray());
    }
    public static MongoClient getMongoClient(List<ServerAddress> addresses, List<MongoCredential> credentials) {
        return new MongoClient(addresses, credentials);
    }
    public static MongoDatabase getMongoDatabase(MongoClient client, String dbName) {
        return client.getDatabase(dbName);
    }
    public static MongoCollection<Document> getMongoCollection(MongoDatabase db, String collName) {
        return db.getCollection(collName);
    }
    public static void MongoOver(MongoClient client) {
        client.close();
    }
    public static MongoClient getMongoClient(MongoObject obj) {
        return new MongoClient(
            getServers(getServerAdress(obj.host, obj.port)),
            getCredentials(getMongoCredential(obj.user, obj.database, obj.password))
        );
    }
    public static MongoClient getMongoClientOnline(MongoObject obj) {
        String uri = String.format(
            "mongodb://%s:%s@%s:%d/%s",
            obj.user, obj.password, obj.host, obj.port, obj.database
        );
        return new MongoClient(new MongoClientURI(uri));
    }
    public static MongoCollection<Document> getCollection(MongoObject obj, String collName) {
        return getMongoClient(obj).getDatabase(obj.database).getCollection(collName);
    }
    public static MongoCollection<Document> getCollectionOnline(MongoObject obj, String collName) {
        return getMongoClientOnline(obj).getDatabase(obj.database).getCollection(collName);
    }
}

MongoObject configuration class

MongoObject

extends MongoBase and stores the connection parameters (host, port, username, password, database). It offers two constructors – one that builds a client from explicit server/credential objects and another that builds a client from a MongoDB URI. The class also provides a method to obtain a collection and a method to close the underlying client.

package com.fun.mongodb;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

public class MongoObject extends MongoBase {
    String host;
    int port;
    String user;
    String password;
    String database;
    MongoClient mongoClient;

    public MongoObject(String host, int port, String user, String password, String database) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = password;
        this.database = database;
        this.mongoClient = getMongoClient(this);
    }

    public MongoObject(int port, String host, String user, String password, String database) {
        this.host = host;
        this.port = port;
        this.user = user;
        this.password = password;
        this.database = database;
        this.mongoClient = getMongoClientOnline(this);
    }

    public MongoCollection<Document> getMongoCollection(String collectionName) {
        MongoClient client = getMongoClientOnline(this);
        return client.getDatabase(database).getCollection(collectionName);
    }

    public void over() {
        MongoOver(this.mongoClient);
    }

    @Override
    public MongoObject clone() {
        return new MongoObject(this.host, this.port, this.user, this.password, this.database);
    }

    public MongoObject clone2() {
        return new MongoObject(this.port, this.host, this.user, this.password, this.database);
    }
}

Typical usage

The following main method demonstrates how to instantiate a MongoObject, retrieve a collection, fetch the first document, print it, and finally close the connection.

public static void main(String[] args) {
    MongoObject ready = new MongoObject("127.0.0.1", 27017, "myUser", "myPass", "myDatabase");
    MongoCollection<Document> coll = ready.getMongoCollection("my_collection");
    Document first = coll.find().first();
    System.out.println(first);
    ready.over();
}

The printed document is a standard BSON representation, e.g.:

Document{{_id=5be4ce052ce01b21b6c26a64, user_id=5482, action_type={"gameId":2,"userId":"5482"}, client_ip=114.5.146.239, ...}}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootCode ExampleMongoDBDatabase Utility
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.