Explore MongoDB in a Java application for basic usage.

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.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Originally published on https://dzone.com

#mongodb #java #web-development

Explore MongoDB in a Java application for basic usage.
1 Likes6.65 GEEK