Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

MongoDB in a Java Application for Basic Usage

DZone 's Guide to

MongoDB in a Java Application for Basic Usage

in this tutorial, explore MongoDB in a Java application for basic usage.

· Database Zone ·
Free Resource

In day-to-day life in the industry, we have data to be saved and fetched from any persistence source. The persistence source can be SQL, NoSQL, or other types. MongoDB is a NoSQL database. Sometimes we need a small tool to look at data or delete data in MongoDB. For quick development, we need a solution/layer/UI that simplifies our task.

MongoDB holds data in the form of a document, so any data that needs to be stored has to be converted into a MongoDB Document, and it's a cumbersome task, in general. To make things easier, we need a helper/util java class. MongoDB Java framework provides a mechanism to implement the same. The following enum class helps to do so. Through this enum class, the data that exists in any POJO can be saved/queried/updated with ease. The enum class can fetch the MongoDB collection data with the default security mechanism.

public enum MongoUtility {

    INSTANCE;

    private final Map<String, MongoDatabase> databaseMap = new HashMap<>();
    private final CodecRegistry pojoCodecRegistry;
    private final MongoClient mongo;

    private MongoUtility() {
        pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
                fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        mongo = new MongoClient();
    }

    public void closeMongoDB() {
        Optional.of(mongo).ifPresent(mongoInstance -> mongoInstance.close());
    }

    public MongoDatabase getDatabase(String database) {
        Optional<MongoDatabase> mongoDBOptional = Optional.ofNullable(databaseMap.get(database));
        return mongoDBOptional.orElseGet(createMongoDatabaseInstance(database));
    }

    private Supplier<MongoDatabase> createMongoDatabaseInstance(String database) {
        return () -> {
            MongoDatabase mongoDB = mongo.getDatabase(database);
            mongoDB = mongoDB.withCodecRegistry(pojoCodecRegistry);
            databaseMap.put(database, mongoDB);
            return mongoDB;
        };
    }

    public <T> MongoCollection<T> getBucket(String database, String bucket, Class<T> cls) {
        MongoDatabase mongoDB = getDatabase(database);
        return mongoDB.getCollection(bucket, cls);
    }
}

The above implementation can be achieved in Maven by putting the dependency in the pom.xml file.

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.10.2</version>
</dependency>

So, the framework can get things done with the least amount of effort.

Topics:
java ,mongodb ,tutorial ,java application ,basic usage ,enum class

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}