Java @ Desk: MongoDB | Java at your desk

Spring Boot with Mongo DB example

Spring Boot with Mongo DB example

This example demonstrates the integration of Mongo DB with Spring Boot. If you are running Mongo DB locally, then there is no need to configure anything for the Mongo database in the spring boot application.

Spring boot auto configures the mongo db configuration since by default mongo runs on
1) host - localhost or 127.0.0.1
2) port - 27017

If you are running a mongo db on local system, then you just have to configure the mongo repository interface in your spring boot application and use @EnableMongoRepositories annotation. Once you run the spring boot application you will notice a following log in your mongo db command prompt
connection accepted from 127.0.0.1:52994 #1 (1 connection now open)

This indicates that the spring boot application is connected to mongo db and you can perform db operations.

And once you stop the application you will observe
end connection 127.0.0.1:52994 (1 connection now open)


In any case there is a need for configuring the change in host or port, then perform following changes in application.properties file
server.port=8070
spring.dao.exceptiontranslation.enabled=false
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017


Here is the maven dependency for spring data for mongo db
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-mongodb</artifactId>
 <version>1.10.1.RELEASE</version>
</dependency>


Spring Boot app java class - This class configures the spring controller file plus enables the mongo repository using @EnableMongoRepositories annotation.
package com.springbootservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.repository.AppRepository;

@SpringBootApplication(scanBasePackages = { "com.controller"})
@EnableMongoRepositories(basePackageClasses = AppRepository.class)
public class App {

 public static void main(String[] args) {
  SpringApplication.run(App.class, args);
 }
}




Repository Interface - Mongo comes with the MongoRepository interface that internally performs all the basic db operations like insert, get & delete on its own. You must have to create a repository interface that extends MongoRepository interface along with the type. If you have mongo db data object Person then MongoRepository enables all basic operations on Person object.
package com.repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.model.Person;

@Repository()
public interface AppRepository extends MongoRepository<Person, String> {

}


Mongo Model class
package com.model;

import org.springframework.data.annotation.Id;

public class Person {
 @Id
 private String id;

 private String name;

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}


Test Controller - Simply autowire the AppRepository object and start performing DB operations as shown below
@Autowired
private AppRepository appRepository;

@RequestMapping(method = RequestMethod.GET, path = "/test/Mongo", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getTest() {
 String temp = "abc";
 Person person = new Person();
 person.setId("Id");
 person.setName("Kumar");
 appRepository.insert(person);

 Person person2 = appRepository.findOne("Id");
 System.out.println("Person - " + person2);
 System.out.println(person2.getName());
 appRepository.delete("Id");
 System.out.println("Deleted Successfully");
 return new ResponseEntity<String>(temp, HttpStatus.OK);

}

Java MongoDB Query, Find Document from Collection with IN clause

Java MongoDB Query, Find Document from Collection with IN clause

To use IN clause in MongoDB, we need to create the list and set the list as value with key as "$in"

In our last post, we learned how to find the document with where clause within a collection. This post will illustrate on how to find documents from a collection using IN clause.

First Insert Records in a Collection.

In the above example, collection Loan is created with 2 parameters :

1) name/type of loan
2) Interest rate

To find a document where name = "Personal Loan" or "Home Loan", we need to use "$in" as a key.

Refer to example :

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;


public class MongoDBFindJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");
  
  // To find a record where Name IN
  BasicDBObject inQuery = new BasicDBObject();
  List<String> list = new ArrayList<String>();
  list.add("Personal Loan");
  list.add("Home Loan");
  inQuery.put("name", new BasicDBObject("$in", list));
  DBCursor cursor = collection.find(inQuery);
  while(cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

Java MongoDB Query, Find Document from Collection with Where clause

Java MongoDB Query, Find Document from Collection with Where clause

In our last post, we learned how to find all the documents within a collection using find() method. This post will illustrate on how to find document from a collection using a where clause to satisfy particular condition.

First Insert Records in a Collection.

In the above example, collection Loan is created with 2 parameters :

1) name/type of loan
2) Interest rate

To find a document with a matching condition, we need to pass an object of BasicDBObject class with the condition. For example, we need to find out all the documents from collection Loans where name = "Personal Loan".

Refer below example to do so

import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;


public class MongoDBFindJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");
  
  // To find a record where Name = Personal Loan
  BasicDBObject whereQuery = new BasicDBObject();
  whereQuery.put("name", "Personal Loan");
  DBCursor cursor = collection.find(whereQuery);
  while(cursor.hasNext()) {
      System.out.println(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

Java MongoDB Query, Find All Documents in a Collection



Java MongoDB Query, Find All Documents in a Collection

To find all the records from a collection in MongoDB, first Insert Records in a Collection.

In the above example, collection Loan is created with 2 parameters :

1) name/type of loan
2) Interest rate

Below example will find all the records from a collection

import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;


public class MongoDBFindJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");

  // To Find All the Records
  DBCursor cursor = collection.find();
  while(cursor.hasNext()) {
      System.out.println("Record - " + cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB Java Insert Document In Collection

MongoDB Java Insert Document In Collection

There are three different ways to insert a document in a collection using Java Driver :
1) com.mongodb.BasicDBObject - Create the new object and keep on appending the fields into the object

2) com.mongodb.BasicDBObjectBuilder - Static method "start()" returns the new instance of the class. Add fields into the object and "get()" method of the class returns the DBObject object that can be inserted into a collection.

3) java.util.Map - Create a Map object and put the values in key, value fashion. Add them into a collection

Java Example :

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;


public class MongoDBInsertJava {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");

  BasicDBObject personalLoanDBObject = new BasicDBObject();
  personalLoanDBObject.append("name", "Personal Loan");
  personalLoanDBObject.append("interest", 10.0);

  collection.insert(personalLoanDBObject);
  
  BasicDBObject homeLoanDBObject = new BasicDBObject();
  homeLoanDBObject.append("name", " Home Loan");
  homeLoanDBObject.append("interest", 12.0);

  collection.insert(homeLoanDBObject);
  
  BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start();
  documentBuilderDetail.add("name", "Personal Loan");
  documentBuilderDetail.add("interest", 10.0);
  
  collection.insert(documentBuilderDetail.get());
  
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("name", "Personal Loan");
  map.put("interest", 10.0);

  collection.insert(new BasicDBObject(map));
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB get minimum value in Java



MongoDB get minimum value in Java

To get/find a minimum value from a collection in MongoDB is similar to getting a min value from a column in SQL.

Corresponding SQL query is similar to this

Select min(Column_Name) from Table_Name


Consider a collection called loan created as below

db.loan.insert( { _id: 10, item: "Personal Loans", interest: 14 } )
db.loan.insert( { _id: 10, item: "Home Loans", interest: 12 } )
db.loan.insert( { _id: 10, item: "Car Loans", interest: 16 } )


Let's find out the loan category having maximum interest rate among the three inserted in the collection above:

This example above has 3 interest rates 12 - Home Loans, 14 - Personal Loans, 16 - Car Loans

To get the minimum loan value use below query

db.loan.find().sort({interest: 1}).limit(1)


Java Example :

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class MongoDBFindMaximum {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");

  DBObject sort = new BasicDBObject();
  sort.put("interest", 1);
  
  DBCursor cursor = collection.find().sort(sort).limit(1);
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB get maximum value in Java



MongoDB get maximum value in Java

To get/find a maximum value from a collection in MongoDB is similar to getting a max value from a column in SQL.

Corresponding SQL query is similar to this

Select max(Column_Name) from Table_Name


Consider a collection called loan created as below

db.loan.insert( { _id: 10, item: "Personal Loans", interest: 14 } )
db.loan.insert( { _id: 10, item: "Home Loans", interest: 12 } )
db.loan.insert( { _id: 10, item: "Car Loans", interest: 16 } )


Let's find out the loan category having maximum interest rate among the three inserted in the collection above:

This example above has 3 interest rates 12 - Home Loans, 14 - Personal Loans, 16 - Car Loans

To get the maximum loan value use below query

db.loan.find().sort({interest: -1}).limit(1)


Java Example :

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class MongoDBFindMaximum {
 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  DBCollection collection = database.getCollection("loans");

  DBObject sort = new BasicDBObject();
  sort.put("interest", -1);
  
  DBCursor cursor = collection.find().sort(sort).limit(1);
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB Drop All Collections From Database in Java

MongoDB Drop All Collections From Database in Java

In our last post, we learned How to drop a collection from MongoDB in Java

drop() method is called on a DBCollection object to drop the entire collection along with the indexes associated.

In order to delete all the collections associated with the database, you need to make use of getCollectionNames() method of class com.mongodb.DB

Java Program:

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

public class MongoDBDropCollection {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  for (String string : database.getCollectionNames()) {
   DBCollection collection = database.getCollection(string);
   collection.drop();
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB Drop Database Java Example

MongoDB Drop Database Java Example

Drop a database removes all the collections and indexes associated plus all data files. It simply cleans up the complete database.

This command obtains a global write lock and will block other operations until it has completed.

To drop a single database :
1) Load the DB object for the database
2) Call the dropDatabase() method

To drop all the database in MongoDB in java :
1) Iterate through the list of database names
2) Load the DB object for the database
3) Call the dropDatabase() method

Java Program :

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoDBDropDatabase {

 public static void main(String args[]) throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  
  // Drop a Single Database
  DB database = mongo.getDB("yourdb");
  database.dropDatabase();

  // Drop all the database
  for (String string : mongo.getDatabaseNames()) {
   DB db = mongo.getDB(string);
   db.dropDatabase();
  }
 }
}

MongoDB Drop Collection Java Example

MongoDB Drop Collection Java Example

In our last post, we learned MongoDB Drop Collection example through command line.

This post explains how to drop or remove a complete collection in a Java Program.

drop() method is called on a DBCollection object to drop the entire collection along with the indexes associated.

dropIndexes() method removes all the indexes of the collection. This method is internally called from above method drop(). No need to explicitly call this.

Below example loads the collection "loans" and drops the collection

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoDBDropCollection {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");

  collection.drop();
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB Remove Delete All Records Documents Java

MongoDB Remove Delete All Records Documents from a Collection in Java

In our last post, we understood MongoDB Remove Delete Record Document Java

What if we want to delete all the documents from a collection?

To implement this two strategies are there
1) Using a new instance of BasicDBObject class - Pass the new object of BasicDBObject to collection.remove() method to delete all the documents from a collection

2) Using DBCursor - DBCursor iterator is used to remove a documents from a collection using a Iterator

Refer example below

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;

public class MongoDBDelete {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();

  DBCollection collection = database.getCollection("loans");

  BasicDBObject document = new BasicDBObject();

  // Delete All documents from collection Using blank BasicDBObject
  collection.remove(document);

  // Delete All documents from collection using DBCursor
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   collection.remove(cursor.next());
  }
 }

 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}

MongoDB Remove Delete Record Document Java

MongoDB Remove Delete Record Document from a Collection in Java

In our last post, we explained how to remove/delete a record/document from a collection in MongoDB from command line

This post provides a sample example to implement the delete functionality for a record or document from a collection in Java

For example, we want to delete a record of a Loan where name = "Personal Loan" from a Loans collection.

To implement this following things are followed in order :
1) Create a DB object
2) Load a collection "loans"
3) Create BasicDBObject object
4) Remove BasicDBObject object from collection object created in step 2

Click here to see MongoDB Remove Delete All Records Documents Java

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;


public class MongoDBDelete {

 public static void main(String args[]) throws UnknownHostException {
  DB database = getDatabase();
  
  DBCollection collection = database.getCollection("loans");
  
  BasicDBObject document = new BasicDBObject();
  document.put("name", "Personal Loan");
  
  WriteResult result = collection.remove(document);
  System.out.println("Number of documents deleted : " + result.getN());
 }
 
 public static DB getDatabase() throws UnknownHostException {
  Mongo mongo = new Mongo("localhost", 27017);
  DB database = mongo.getDB("yourdb");
  return database;
 }
}


Click here to see MongoDB Remove Delete All Records Documents Java

MongoDB Drop Collection example

MongoDB Drop Collection example

To drop a collection i.e. delete the complete collection as well as remove all the indexes use the below command

db.collection.drop()


This method do not take any argument. It also applies lock on the database and other operations will be in wait state until this gets finished.

MongoDB Remove Delete Document Record From Collection

MongoDB Remove Delete Document Record From Collection

To remove/delete a record/document from MongoDB following command is used

db.collection.remove()


The remove function accepts 2 arguments
1) query document
2) justOne

Different ways to delete a document from collection are :
1) Remove All Documents from a Collection - In this case empty query parameter passed in the remove method are deleting all the documents from a collection. This is not equivalent to the drop() method which removes the collection as well as indexes associated with the collection

2) Remove All Documents that satisfy a given Condition - Query parameter for which the document need to be removed is passed in the remove method

3) Remove a Single Document that satisfy a given Condition - This is similar to the second option with an additional parameter of justOne parameter set to true or 1.

Example :
1) Remove All Documents from a Collection
db.loans.remove( { } )


2) Remove All Documents that satisfy a given Condition
db.loans.remove({'name':'Personal Loan'})
db.loans.remove({'name':'Home Loan'})


3) Remove a Single Document that satisfy a given Condition
db.loans.remove({'name':'Personal Loan'}, true )

MongoDB Insert Multiple Documents

MongoDB Insert Multiple Documents

In our last post, we learn how to Insert Document in MongoDB. In this post, we will learn to insert multiple documents at once.

db.loans.insert(
   [
     { <RECORD> },
     { <RECORD> },
     { <RECORD> }
   ]
)


This will insert 3 records in the collection loans.

db.loans.insert(
   [
     { { item: "home", interest: 10 } },
     { { _id: 10, item: "personal", interest: 14 } }
   ]
)


This will insert 2 records in the collection loans and in 1st case it will create unique ObjectId. Following records will be inserted

{ <b>"_id" : ObjectId("51e0373c6f35bd826f47e9a0")</b>, item: "home", interest: 10 } 
{ _id: 10, item: "personal", interest: 14 }

MongoDB Insert Document example

MongoDB Insert Document example

In MongoDB, a single document or multiple documents can be inserted into a collection by provinding a DB and a collection in the insert command.

The data points are stored in a collection specified. If the database or collection does not exists, they will automatically be created when the first data insert command is executed i.e. when we call

db.collection.insert()


Syntax for inserting a document :

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)


If the collection does not exists, it creates a new collection and insert records into it.

There are 2 ways to run an insert command
1) Providing the _id field
2) Without providing _id field - During the insert, mongod will create the _id field and assign it a unique ObjectId value, as verified by the inserted document

For Example
Inserting a document without providing _id field : In this case, MongoDB will create a unique ObjectId as shown below
db.loan.insert( { item: "home", interest: 10 } )

{ "_id" : ObjectId("5063114bd386d8fadbd6b004"), "item" : "home", "interest" : 10 }


Inserting a document with _id field : In this case, MongoDB will create a unique ObjectId as shown below
db.loan.insert( { _id: 10, item: "personal", interest: 14 } )

{ "_id" : 10, "item" : "personal", "interest" : 14 }