Explore MongoDB in a Java application for basic usage.

Explore MongoDB in a Java application for basic usage.

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine.

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

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Developing Apps with MongoDB and Java

Want to get started with MongoDB and Java? Developing Apps with MongoDB and Java - Learn how to set up your Java project with Maven and execute a MongoDB command in Java.

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.