SprinBoot with MongoDB

Home / SprinBoot with MongoDB

As we all know MongoDB is a No SQL database, springboot provides a MongoTemplate object to perform MongoDB operations. We just have to autowired this object in our service class. In this example we will see how to perform MongoDB CRUD operations in SpringBoot with MongoTemplate.

For performing MongoDB queries operations in springboot we have to follow some steps:

1- create a springboot project and add the following dependencies in your pom.xml file.

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
 </dependency>

2- After adding dependency in pom.xml file go to application.properties file and add following lines.

spring.data.mongodb.database=vasuMongoDB
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

3- create a service class and autowired the object of MongoTemplate class.

@Autowired
 private MongoTemplate template;

4- perform database crud operation using this template object .

We are creating a mongoDb crud application for user data. you can see the complete code on Github

SAVE Data:

@Override
public JSONObject save(JSONObject payload) {
        try {
            Document condition = new Document();
            String fName = payload.get(Collections.userCollection.FIRST_NAME).toString();
            String lName = payload.get(Collections.userCollection.LAST_NAME).toString();
            String email = payload.get(Collections.userCollection.EMAIl).toString();
            condition.clear();
            condition.append(Collections.userCollection.FIRST_NAME, fName)
                    .append(Collections.userCollection.LAST_NAME, lName)
                    .append(Collections.userCollection.EMAIl, email);

            
            MongoCollection<Document> collection = template.getCollection(Collections.userCollection.COLLECTION_NAME);
            collection.insertOne(condition);
            Object getInsertId = condition.get("_id");
            logger.info("vvv::  insertId= " + getInsertId);
            if (getInsertId.toString().equals("")) {
                return responses.getResponse(responses.ERROR);
            }
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find All Data:

  public Object getAll() {
        try {
            condition.clear();
            condition.append(Collections.userCollection.EMAIl, new Document("$ne", ""));
            Object findAll = find(condition, Collections.userCollection.COLLECTION_NAME);
            return findAll;
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

FindBy id:

 public Object find(Document condition, String collectionName) {
        try {
            FindIterable<Document> find = template.getCollection(collectionName).find(condition);
            MongoCursor<Document> iterator = find.iterator();
            Document docsResponse = new Document();
            JSONArray responseArr = new JSONArray();
            while (iterator.hasNext()) {
                responseArr.add((JSONObject) parser.parse(iterator.next().toJson().trim()));
            }
            if (responseArr.size() > 0) {
                return responseArr;
            }
            return null;
        } catch (Exception e) {
            logger.error(e, e);
            return null;
        }
    }

Delete Data:

      public JSONObject delete(Document condition, String collectionName) {
        try {
            Document findOneAndDeleteResponse = template.getCollection(collectionName).findOneAndDelete(condition);
            return responses.getResponse(responses.OK);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Update Data:

public JSONObject update(JSONObject whereObj, JSONObject updateObj, String collectionName) {
        try {
            logger.info("vvv::  whereObj= " + whereObj + ", updateObj= " + updateObj + ", collName= " + collectionName);
            if (whereObj == null || updateObj == null || collectionName == null) {
                logger.info("vvv::  insufficentData");
                return responses.getResponse(responses.INSUFFICIENT_DATA);
            }
            Query query = new Query();
            Update update = new Update();

            //iterate where Condition
            Set keySet = whereObj.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                query.addCriteria(Criteria.where(key).is(whereObj.get(key)));
            }

            //iterate Update Value
            Set updateSet = updateObj.keySet();
            Iterator updateItr = updateSet.iterator();
            while (updateItr.hasNext()) {
                String key = (String) updateItr.next();
                update.set(key, updateObj.get(key));
            }
            logger.info("vvv::  query= " + query.toString());
            logger.info("vvv::  update= " + update.toString());
            UpdateResult updateMulti = template.updateMulti(query, update, collectionName);
            logger.info("vvv::  updateMulti= " + updateMulti);
            if (updateMulti.getModifiedCount() == 1) {
                return responses.getResponse(responses.OK);
            }
            return responses.getResponse(responses.ERROR);
        } catch (Exception e) {
            logger.error(e, e);
            return responses.getResponse(responses.ERROR);
        }
    }

Find Complete Code on Github

https://github.com/vasurajput/JavaDream/tree/master/SpringBootMongoDB
Help Others, Please Share

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

x