BLOGs
Design & Development
Published October 31st, 2016 by

Java 8 Crud Opration with Mongodb 3.2

mongodb-3-2

This article we cover create read update delete operation with mongodb database. Before going further you have basic knowledge of core java and database concept.

Have you heard of Create Read Update Delete operation of Java 8? In this post, developers will explain the concept of Core java and Mongo Database. They will also share step by step guide to explain CRUD operation. You must hire java programmers to perform this tutorial for better understanding.

MonogDB

Mongodb is one a most popular nosql database in market. What do you mean by nosql? Structure and unstructured data combination is nosql.here in nosql will store all type of data without any fixed format and without any relationship like SQL database. We cover mongodb 3.2 version and you can download mongodb official website base on your operating system. For installation and configuration mongodb website explain step by step explanations.

MONGODB BASIC TERMINOLOGY

We didn’t explicit create Database and collection (table) manually in MongoDB.it will automatically create when we pass from code.

MongoDB Every collection format was not same it would be different base on records that will insert and not any restriction of size.

MongoDB store value KEY VALUE pair in JSON format.

JAVA CRUD STEP BY STEP

package com.test;

import com.mongodb.MongoClient;

import com.mongodb.client.MongoDatabase;

public class DatabaseConnection {

    private static MongoDatabase  dbConnection = null;

    private DatabaseConnection() {}

      @SuppressWarnings("resource")

       public static MongoDatabase getDatabaseConnection() {

          if(dbConnection == null) {

            MongoClient mongoClient = new MongoClient("localhost", 27017);

              dbConnection = mongoClient.getDatabase("Employee");
         }
         return dbConnection;
      }
}

This is mongodb database connection class.mongodb running on 27017(default) port.

MongoClient mongoClient = new MongoClient(“localhost”, 27017);

You can put your datebase insted of “localhost” and port.

dbConnection = mongoClient.getDatabase(“Employee”);

You can put your database name instead of “employee”.

This class object was required when do any database operation and single object was given to every time not new object was create. Object also destroy and release resource when database work complete automatically.

package com.test;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import org.bson.Document;

import org.bson.types.ObjectId;

import com.test.DatabaseConnection;

import com.mongodb.BasicDBObject;

import com.mongodb.client.FindIterable;

import com.mongodb.client.result.DeleteResult;

import com.mongodb.client.result.UpdateResult;

import com.mongodb.util.JSON;

public class MongoCRUD {

This is save method where we insert record in mongoDB first argument contain key value pair and second contain collection (table) name where you insert a records.

Document is class that collect records for hash map where we iterate map and using Lambda expression (–>) we insert records in documents. Using Database Connection class we take object of database and insert records via documents.

public static boolean save(final HashMap<String,String> keyValue,final String dbCollection) {

        if(keyValue!=null){

            Document document = new Document();

            keyValue.forEach((k,v)->document.append(k, JSON.parse(v)));

            DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).insertOne(document);

            return true;
        }
     return false;
   }

This method is for select record form database. You can pass record in hashmap and collection name.it will search and get back result.

public static HashMap<String, String> getfirst(final HashMap<String,String> searchKeyValue,final String dbCollection) {

       HashMap<String, String> hashMap = new HashMap<>();

    if(searchKeyValue!=null){

        Document document = new Document();

        searchKeyValue.forEach((k,v)->document.append(k, JSON.parse(v)));

        Document DocumentRecord = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).find(document).first();

        DocumentRecord.forEach((k,v)->hashMap.put(k, v.toString()));

        }
       return hashMap;
   }

This methods for update records base on search criteria you have passed in hashmap.

public static void update(final HashMap<String,String> searchKeyValue, final HashMap<String, String> updatedValue,final String dbCollection) {

        UpdateResult updateResult = null;

        Document searchdocument = new Document();

        Document updateDocument = new Document();

        searchKeyValue.forEach((k,v)->searchdocument.append(k, JSON.parse(v)));

        updatedValue.forEach((k,v)->updateDocument.append(k, JSON.parse(v)));

        updateResult = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).updateOne(new Document(searchdocument),new Document("$set",new Document(updateDocument)));
   }

This is Delete Method via Hashmap you passed your json and it will delete from collection if they match that records.

public static boolean deleteone(final HashMap<String, String> searchKeyValue,final String dbCollection) {

       DeleteResult deleteResult = null;

        if(searchKeyValue!=null ){

            Document document = new Document();

            searchKeyValue.forEach((k,v)->document.append(k,JSON.parse(v)));

            deleteResult = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).deleteOne(document);

            System.out.println(deleteResult.toString());

            return true;
        }
      return false;
   }

This is basic CRUD method of MongoDB apart from that they have many flavours in Crud I will explain you some more method for your specific operation in CRUD.

Some more methods

INSERT

This is Insert method but will insert bulk records. For that we you insert many method

  public static Boolean save(final List<HashMap<String, String>> insertLists,final String dbCollection) {

       if(insertLists!=null){

           List<Document> documents = new ArrayList<>();

           for(int i=0;i<insertLists.size();i++){

               Document document = new Document();

               insertLists.get(i).forEach((k,v)->document.append(k, JSON.parse(v)));

               documents.add(document);
           }

           DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).insertMany(documents);

        return true;
       }
     return false;
   }

This is same method but input was different previously it was list + hash map but this was direct document with List

public static Boolean saveDocuments(final List<Document> documents,final String dbCollection) {

       if(documents!=null){

           DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).insertMany(documents);

        return true;
       }
     return false;
   }

Select

This method get all record form table

public static List<HashMap<String, String>> getAll(final String dbCollection) {

      FindIterable<Document> documents = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).find();

      List<HashMap<String,String>> getAllRecords = new ArrayList<>();

      for (Document document : documents) {

          HashMap<String, String> hashMap = new HashMap<>();

         document.forEach((k,v)->hashMap.put(k, v.toString()));

         getAllRecords.add(hashMap);

      }
      return getAllRecords;
   }

This method get first record form match criteria.

public static HashMap<String, String> getfirst(final HashMap<String,String> searchKeyValue,final String dbCollection) {

       HashMap<String, String> hashMap = new HashMap<>();

    if(searchKeyValue!=null){

        Document document = new Document();

        searchKeyValue.forEach((k,v)->document.append(k, JSON.parse(v)));

        Document DocumentRecord = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).find(document).first();

        DocumentRecord.forEach((k,v)->hashMap.put(k, v.toString()));

        }
       return hashMap;
   }

DELETE

This method delete all records from collection base on match criteria

public static boolean deleteall(final String key, final String value,final String dbCollection) {

        DeleteResult deleteResult = null;

        if(key!=null && value!=null){

            deleteResult = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).deleteMany(new Document(key, value));

            System.out.println(deleteResult.toString());

            return true;
        }
        return false;
   }

This method find and delete the records base on match criteria in parameters

public static boolean delete(final String key,final String value,final String dbCollection) {

        Document deleteResult = null;

        if(key!=null && value!=null){

            deleteResult = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).findOneAndDelete(new Document(key, value));

            System.out.println(deleteResult);

            return true;
        }
        return false;
   }

UPDATE

This method update all records that match with criteria we passed in parameters

public static void updateAll(final String key,final String value,final String updatevalue,final String dbCollection){

    UpdateResult updateResult = null;

    if(key!=null && value!=null && updatevalue!=null)

    {

        updateResult = DatabaseConnection.getDatabaseConnection().getCollection(dbCollection).updateMany(new Document(key, value),new Document("$set", new Document(key, updatevalue)));

        System.out.println(updateResult);

    }
}

Basic MongoDb Command

Connect mongoDB server console

mongdb

how many database was available

show dbs

how many tables(collection in database

show collections

mongodb select query

db.collectionname.find().pretty()

Conclusion:

In this article hire java programmers shared their best knowledge about MongoDB and CRUD operation. They cover create read update delete operation with mongodb database. Don’t forget to share your reviews regarding this tutorial with us.

 

Johnny Morgan

Technical Writer at Aegis Infoways
Johnny Morgan as a technical writer at Aegis Infoways since more than 5 years. I write articles especially for Java, Python and Asp.Net. I have also got well response to write articles on CRM, Hadoop and QA.

Our rankings are completely independent, transparent, and community driven; they are based on user reviews and client sentiment. These design & development companies had to earn their way up and didn't just pay their way up.

View Rankings of Best Design & Development Companies