dineshonjava

Spring Data MongoDB : Update document

In this tutorial we will discuss about the updating the document to the mongoDB. Document is same as a row in the table of relational database. In the our example we will update a document to "dojCollection" of "dineshonjavaDB".

Updating documents in a collection-
For updates we can elect to update the first document found using MongoOperation's method updateFirst or we can update all documents that were found to match the query using the method updateMulti.

Here is an example of an update of salary of all employees where employee age is 24 and we are adding a one time $50.00 bonus to the salary using the $inc operator.
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;

          ...

  WriteResult wr = mongoTemplate.updateMulti(
new Query(where("empAge").is(24)),new Update().inc("salary", 50.00),Employee.class);
Methods for executing updates for documents:
1. updateFirst Updates the first document that matches the query document criteria with the provided updated document.
2. updateMulti Updates all objects that match the query document criteria with the provided updated document.

Methods for the Update class

The Update class can be used with a little 'syntax sugar' as its methods are meant to be chained together and you can kickstart the creation of a new Update instance via the static method public static Update update(String key, Object value) and using static imports.
Here is a listing of methods on the Update class
  • Update addToSet (String key, Object value) Update using the $addToSet update modifier
  • Update inc (String key, Number inc) Update using the $inc update modifier
  • Update pop (String key, Update.Position pos) Update using the $pop update modifier
  • Update pull (String key, Object value) Update using the $pull update modifier
  • Update pullAll (String key, Object[] values) Update using the $pullAll update modifier
  • Update push (String key, Object value) Update using the $push update modifier
  • Update pushAll (String key, Object[] values) Update using the $pushAll update modifier
  • Update rename (String oldName, String newName) Update using the $rename update modifier
  • Update set (String key, Object value) Update using the $set update modifier
  • Update unset (String key) Update using the $unset update modifier
 In Spring data for MongoDB, you can use save(), updateFirst() and updateMulti() to update existing domain object from mongoDB database.
Employee employee = new Employee("...");
 
 //update employee object into entity collection
 mongoOperation.save(employee);
 
 //update employee object into "newCollection" collection
 mongoOperation.save("newCollection",employee);
 
 //update first found record, empName field, where empId = 1004,
 //from your default collection
 mongoOperation.updateFirst(
  new Query(Criteria.where("empId").is(1004)),
  Update.update("empName", "new name"));
 
 //update first found record, empName field, where empId = 1004,  
 //from collection named "employee"
 mongoOperation.updateFirst("employee",
  new Query(Criteria.where("empId").is(1004)),
  Update.update("empName", "new name"));
 
 //update all found records, salary field, where empAge = "24",  
 //from collection named "employee"
 mongoOperation.updateMulti("employee",
  new Query(Criteria.where("empAge").is(24)),
  Update.update("salary", 70000));
 
 //update first found record, age field, where empId = 1001, using $inc  
 Update updateAge = new Update();
 updateAge.inc("age", 10);
 
 mongoOperation.updateFirst("employee",
  new Query(Criteria.where("empId").is(1001)), updateAge);

Note: By default, if you didn’t define the collection name in updateFirst or updateMulti method, it will update the found object in default collection.

See the full example to insert document into the "dojCollection" of the "dineshonjavaDB"
Spring Data MongoDB : Update document

Step 1: Creating the domain class Employee
Employee.java  
package com.dineshonjava.mongo.dto;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author Dinesh Rajput
 *
 */
@Document
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}

Step 2: Creating configuration file
mongo-config.xml


<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
  
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
 <mongo:mongo>
  <mongo:options connections-per-host="100"
   threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 </mongo:mongo>
 
 <context:annotation-config/>
     
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
   <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   </bean>
    
</beans>

Step 3: Creating Class which inserting the document into the mongoDB.
HelloMongoDB.java
package com.dineshonjava.mongo.main;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  // Case1 - insert a employee, put "DOJ" as collection name 
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Anamika Rajput");
  employee.setSalary(30000);
  employee.setEmpAge(23);
  
  mongoOperations.save(employee, "DOJ");
     
  // find
  Employee employee1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employee1);
   
  // Update employee object, salary
  employee1.setSalary(35000);
  mongoOperations.save(employee1, "DOJ");
   
  // find
  Employee employeeupdated = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employeeupdated);
  
  // Case 2 ... update salary field, $set
  Employee employee2 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"orders");
  System.out.println(employee2);
     
  // Update employee object, salary
  System.out.println("Case 2...by updateFirst() - $set");
   
  mongoOperations.updateFirst(query(where("empId").is(1001)), Update.update("salary", 40000),"orders");
    
  // find
  Employee employeeupdated1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"orders");
  System.out.println(employeeupdated1);
  
  // Case 3 ... update salary field, $inc
  System.out.println("Case 3...by updateFirst() - $inc");
  Update updateSalary = new Update();
  updateSalary.inc("salary", 1000);
  mongoOperations.updateFirst(query(where("empId").is(1001)), updateSalary, "orders");
  Employee employee3 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class);
  System.out.println(employee3);
 }
}

Step 4: Running the Example
Following code shows how to run this example

HelloMongoTestApp.java
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloMongoTestApp {

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.

output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=30000]
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=35000]
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]
Case 2...by updateFirst() - $set
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=90000]
Case 3...by updateFirst() - $inc
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=100000]
DONE!

Download SourceCode+Libs
MongoDBSpringUpdateDemo.zip

References
Spring data for MongoDB


                             <<previous<<             || index  ||         >>next>>


Spring Data MongoDB Insert document

In this tutorial we will discuss about the inserting document to the mongoDB. Document is same as a row in the table of relational database. In the our example we will insert a document to "dojCollection" of "dineshonjavaDB".

Methods for saving and inserting documents-
There are several convenient methods on MongoTemplate for saving and inserting your objects. To have more fine grained control over the conversion process you can register Spring converters with the MappingMongoConverter,
for example Converter<Employee, DBObject> and Converter<DBObject, Employee>.

Note: The difference between insert and save operations is that a save operation will perform an insert if the object is not already present.
1. save” is means “insert it if record is not exists” and “update it if record is existed”, or simply saveOrUpdate().
2. insert” is means “insert it if record is not exits” and “ignore it if record is existed”.

The simple case of using the save operation is to save a POJO. In this case the collection name will be determined by name (not fully qualfied) of the class. You may also call the save operation with a specific collection name. The collection to store the object can be overridden using mapping metadata.

When inserting or saving, if the Id property is not set, the assumption is that its value will be autogenerated by the database. As such, for autogeneration of an ObjectId to succeed the type of the Id property/field in your class must be either a String, ObjectId, or BigInteger.

In Spring data for MongoDB, you can use save(), insert() and insertList() to save domain object into mongoDB database.
Employee employee = new Employee("...");
 
 //save employee object into "employee" collection
 mongoOperation.save(employee);
 
 //save employee object into "newCollection" collection
 mongoOperation.save("newCollection",employee );
 
 //save employee object into "employee" collection
 mongoOperation.insert(employee);
 
 //save employee object into "newCollection" collection
 mongoOperation.insert("newCollection", employee );
 
 //save list of employee objects into "employee" collection
 mongoOperation.insertList(employeeInList);
 
 //save list of employee objects into "newCollection" collection
 mongoOperation.insertList("newCollection", employeeInList);


The insert/save operations available to you are listed below.
  • void save (Object objectToSave) Save the object to the default collection.
  • void save (Object objectToSave, String collectionName) Save the object to the specified collection.
A similar set of insert operations is listed below
  • void insert (Object objectToSave) Insert the object to the default collection.
  • void insert (Object objectToSave, String collectionName) Insert the object to the specified collection.
  • insertAll Takes a Collection of objects as the first parameter. This method ispects each object and inserts it to the appropriate collection based on the rules specified above.

Note: By default, if you saved an object, and didn’t define any of the "collection name", it will use the domain object name as the collection name. See the "save" method on mongoTemplate.
public void save(Object objectToSave) {
   save(getEntityCollection(objectToSave), objectToSave);
}

See the full example to insert document into the "dojCollection" of the "dineshonjavaDB".
Spring Data MongoDB Insert document

Step 1: Creating the domain class Employee
Employee.java
package com.dineshonjava.mongo.dto;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author Dinesh Rajput
 *
 */
@Document(collection = "dojCollection")
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}

Step 2: Creating configuration file
mongo-config.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
  
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
 <mongo:mongo>
  <mongo:options connections-per-host="100"
   threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 </mongo:mongo>
 
 <context:annotation-config/>
     
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
   <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   </bean>
   
</beans>

Step 3: Creating Class which inserting the document into the mongoDB.
HelloMongoDB.java
package com.dineshonjava.mongo.main;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  // Case1 - insert a employee, put "DOJ" as collection name 
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Anamika Rajput");
  employee.setSalary(30000);
  employee.setEmpAge(23);
  
  mongoOperations.save(employee, "DOJ");
     
  // find
  Employee employee1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"DOJ");
  System.out.println(employee1);
   
  // Case2 - insert a employee, put entity as collection name 
  Employee employee2 = new Employee();
  employee2.setEmpId(1002);
  employee2.setEmpName("Dinesh Rajput");
  employee2.setSalary(70000);
  employee2.setEmpAge(26);
  
  mongoOperations.save(employee2);
     
  // find
  Employee employee3 = mongoOperations.findOne(query(where("empId").is(1002)), Employee.class);
  System.out.println(employee3);
  
  // Case3 - insert a list of employees
  Employee employee4 = new Employee();
  employee4.setEmpId(1003);
  employee4.setEmpName("Adesh Rajput");
  employee4.setSalary(30000);
  employee4.setEmpAge(23);
  
  Employee employee5 = new Employee();
  employee5.setEmpId(1004);
  employee5.setEmpName("Vinesh Rajput");
  employee5.setSalary(32000);
  employee5.setEmpAge(23);
  
  Employee employee6 = new Employee();
  employee6.setEmpId(1005);
  employee6.setEmpName("Sweety Rajput");
  employee6.setSalary(50000);
  employee6.setEmpAge(22);
  
  List<Employee> empList = new ArrayList<Employee>();
  empList.add(employee4);
  empList.add(employee5);
  empList.add(employee6);
 
  mongoOperations.insert(empList, "Employee-List");
 
List<Employee> results = mongoOperations.find(query(where("empAge").is(23)), Employee.class, "Employee-List");
  System.out.println("Results: " + results);
  
 }
}

Step 4: Running the Example
Following code shows how to run this example

HelloMongoTestApp.java
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloMongoTestApp {

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.
output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Employee [age=23, empName=Anamika Rajput, empId=1001, salary=30000]
Employee [age=26, empName=Dinesh Rajput, empId=1002, salary=70000]
Results: [Employee [age=23, empName=Adesh Rajput, empId=1003, salary=30000], Employee [age=23, empName=Vinesh Rajput, empId=1004, salary=32000]]
DONE!


Download SourceCode+Libs
MongoDBSpringInsertDemo.zip

References
Spring data for MongoDB


                             <<previous<<             || index  ||         >>next>>


Spring Data MongoDB Hello World Example

In this tutorial, we will show how to configure MongoDB using Spring Data. And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data.

For this you have to do the following steps.
Step 1: First you have to Install MongoDB to you system. For windows installation click here.
Step 2: Now add the following tools and libraries for minimum requirement of this example.
  • JDK/Java 1.6 or later
  • SpringSource Tool Suite or later
  • spring-data-mongodb-1.0.2.RELEASE (download it from here)
  • spring-data-commons-core-1.2.0.RELEASE (download it from here)
  • java mongodb driver 2.10.1 (dowload it from here)
  • spring-core-3.1.1.RELEASE
  • spring-context-3.1.1.RELEASE
  • spring-asm-3.1.1.RELEASE
  • spring-expression-3.1.1.RELEASE
  • spring-aop-3.1.1.RELEASE
  • spring-tx-3.1.1.RELEASE
  • cglib-nodep-2.1.3
Spring Data MongoDB Hello World Example

Step 3: Spring XML configuration file (mongo-config.xml):
This spring configuration file contains related bean configurations in order to run this example.
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
  
 <!-- Default bean name is 'mongo' -->
 <mongo:mongo host="localhost" port="27017"/>
  <!-- Default bean name is 'mongo' -->
 <mongo:mongo>
   <mongo:options connections-per-host="100"
  threads-allowed-to-block-for-connection-multiplier="5"
            max-wait-time="120000000"
            connect-timeout="10000000"
            socket-keep-alive="true"
            socket-timeout="15000000"
            auto-connect-retry="true"/>
 </mongo:mongo>
 
 <context:annotation-config/>
     
    <context:component-scan base-package="com.dineshonjava.mongo">
      <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
 <!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->
  <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
       <constructor-arg ref="mongo"/>
         <constructor-arg name="databaseName" value="dineshonjavaDB"/>
   </bean>
    
</beans>
The MongoTemplate is configured with a reference to a MongoDBFactoryBean (which handles the actual database connectivity) and is setup with a database name used for this example.

Step 4: Domain Objects or Classes-

Employee.java represent domain classe which spring data will use to convert them from/to mongodb representation.

Employee.java
package com.dineshonjava.mongo.dto;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * @author Dinesh Rajput
 *
 */
@Document(collection = "dojCollection")
public class Employee {
 @Id
 private int empId;
 private String empName;
 private long salary;
 private int empAge;
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public long getSalary() {
  return salary;
 }
 public void setSalary(long salary) {
  this.salary = salary;
 }
 public int getEmpAge() {
  return empAge;
 }
 public void setEmpAge(int empAge) {
  this.empAge = empAge;
 }
 @Override
 public String toString() {
  return "Employee [age=" + empAge + ", empName=" + empName + ", empId="
    + empId + ", salary=" + salary + "]";
 }
}
Now if you look at the class more closely you will see some Spring Data specific annotations like @Id and @Document . The @Document annotation identifies a domain object that is going to be persisted to MongoDB. Now that we have a persistable domain object we can move on to the real interaction.

Step 5: For easy connectivity with MongoDB we can make use of Spring Data's MongoTemplate class. Here is a simple HelloMongoDB object that handles all 'Employee' related interaction with MongoDB by means of the MongoTemplate.

HelloMongoDB.java
package com.dineshonjava.mongo.main;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Repository;

import com.dineshonjava.mongo.dto.Employee;

/**
 * @author Dinesh Rajput
 *
 */
@Repository
public class HelloMongoDB {
 
 @Autowired
 MongoOperations mongoOperations;
 
 public void execute() {
  if (mongoOperations.collectionExists(Employee.class)) {
   mongoOperations.dropCollection(Employee.class);
   }
   
  mongoOperations.createCollection(Employee.class);
   
  Employee employee = new Employee();
  employee.setEmpId(1001);
  employee.setEmpName("Dinesh Rajput");
  employee.setSalary(70000);
  employee.setEmpAge(26);
  
  mongoOperations.insert(employee);
   
  List<Employee> results = mongoOperations.findAll(Employee.class);
  System.out.println("Results: " + results);
 }
}

Step 6: Running the Example
Following code shows how to run this example

HelloMongoTestApp.java
package com.dineshonjava.mongo.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloMongoTestApp {

 /**
  * @param args
  */
 public static void main(String[] args) {
   ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml");
   
   HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB");
   hello.execute();
   System.out.println( "DONE!" );
 }

}

If everything is fine then run the above main application as Java Application we will get the following output.
output:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Results: [Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]]
DONE!


Download SourceCode + Libs
MongoDBSpringHelloExample.zip

References
Spring data for MongoDB


                             <<previous<<             || index  ||         >>next>>

Authentication to MongoDB with Java

MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with a MongoClient instance:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);
If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.

Most users run MongoDB without authentication in a trusted environment.In this tutorial, we show you how to start MongoDB in secure mode (authentication access is require), and uses Java driver to connect MongoDB with provided username and password.

1. Start MongoDB in Secure Mode
Create an user “dineshonjava” in MongoDB database “dineshonjavaDB”.
> use dineshonjavaDB
> db.addUser("dineshonjava","password")
Authentication to MongoDB with Java

To start mongoDB in secure mode, just provide the "–auth" argument
> mongod --auth
2. Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).
if you try to access the auth db then we will get following.
> db.auth("dineshonjava","password")
1
> db.auth("dineshonjava","password1")
Error: { errmsg: "auth fails", ok: 0.0 }
0
>
Authentication to MongoDB Java

3. Java connect MongoDB
In Java, you can use "db.authenticate" to handle the MongoDB authentication.
DB db = mongo.getDB("dineshonjavaDB");
boolean auth = db.authenticate("dineshonjava", "password".toCharArray());

If username and password is valid, "auth" will be true, else it will be false and return the following error pattern
com.mongodb.MongoException: unauthorized db:dineshonjavaDB lock type:-1 client:192.168.1.3
 at com.mongodb.MongoException.parse(MongoException.java:82)
 at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:302)
 at com.mongodb.DBCursor._check(DBCursor.java:354)
 at com.mongodb.DBCursor._hasNext(DBCursor.java:484)
 at com.mongodb.DBCursor.hasNext(DBCursor.java:509)
 at com.dineshonjava.mongo.test.MongoAuthDemo.main(MongoAuthDemo.java:24)


See the full example as follows.
package com.dineshonjava.mongo.test;

import java.net.UnknownHostException;

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

/**
 * @author Dinesh Rajput
 *
 */
public class MongoAuthDemo {

 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
  boolean auth = db.authenticate("dineshonjava", "password".toCharArray());
  DBCollection collection = db.getCollection("empCollection");
  if(auth){
   System.out.println("TRUE");
  }else{
   System.out.println("FALSE");
  }
   
  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}

If everything is fine then we will get the following output-
output-
TRUE
Done

Download Source Code + Libs
MongoDBAuthDemo.zip

References
MongoDB Java Authentication
MongoDB Security and Authentication



                             <<previous<<             || index  ||         >>next>>

Spring Data MongoDB Examples

In this tutorial we will look about some examples of Spring Data - MongoDB integration. How to Spring configure with NoSQL database and what the advantages of this we will explain in this chapter.

Getting started with MongoDB and Spring Data -
The primary goal of the Spring Data project is to make it easier for developers to work with (No)SQL databases. The Spring Data project already has support for a number of  NoSQL type of databases.

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for for new datastores while retaining store-specific features and capabilities. The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

Spring Data


Spring Data makes it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services as well as provide improved support for relational database technologies.
Spring Data is an umbrella open source project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.

Features

  • Spring configuration support using Java based @Configuration classes or an XML namespace for a Mongo driver instance and replica sets.
  • MongoTemplate helper class that increases productivity performing common Mongo operations. Includes integrated object mapping between documents and POJOs.
  • Exception translation into Spring's portable Data Access Exception hierarchy
  • Feature Rich Object Mapping integrated with Spring's Conversion Service
  • Annotation based mapping metadata but extensible to support other metadata formats
  • Persistence and mapping lifecycle events
  • Low-level mapping using MongoReader/MongoWriter abstractions
  • Java based Query, Criteria, and Update DSLs
  • Automatic implementation of Repository interfaces including support for custom finder methods.
  • QueryDSL integration to support type-safe queries.
  • Cross-store persistance - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
  • Log4j log appender
  • GeoSpatial integration
  • Map-Reduce integration
  • JMX administration and monitoring
  • CDI support for repositories
  • GridFS support

There are below the list of Spring Data and MongoDB examples. Spring Data for MongoDB examples to perform insert, update, query and delete documents from MongoDB.

1. Spring Data MongoDB hello world example
Configure (both XML and annotation) and perform CRUD operations with “Spring Data for MongoDB” framework.

2. Spring Data MongoDB : Insert document
Example to use Spring data save(), insert() and insertList() to save domain object into mongoDB database.

3. Spring Data MongoDB : Update document
Example to use Spring data save(), updateFirst() and updateMulti() to update existing domain object from mongoDB database.

4. Spring Data MongoDB : Query document
Example to use Spring data findOne(), find() and getCollection() to get / query documents from mongoDB.

5. Spring Data MongoDB : Delete document
Example to remove() and findAndRemove() to delete document from mongoDB.


References

  1. MongoDB official site
  2. Java MongoDB official tutorials
  3. Java development with MongoDB
  4. Spring data for MongoDB
  5. Spring data for MongoDB documentation



Java MongoDB Convert JSON data to DBObject

In this tutorial we will see that JSON format convert to the DBObject of MongoDB. Using "com.mongodb.util.JSON" class to convert JSON data directly to a DBObject.
For example, data represent in JSON format :
{
   "empName" : "Dinesh Rajput",
   "empAge"  : 26,
   "salary"  : 70000
}
To convert it to DBObject, you can code like this :
DBObject dbObject = (DBObject) JSON.parse("{"empName" : "Dinesh Rajput",
   "empAge"  : 26,
   "salary"  : 70000}");

Create a Java class to convert JSON Data To DBObject.
package com.dineshonjava.mongo.test;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * @author Dinesh Rajput
 *
 */
public class JSONDocumentDemo {

 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
 
  // get a single collection
  DBCollection collection = db.getCollection("empCollection");

  // convert JSON to DBObject directly
  DBObject dbObject = (DBObject) JSON.parse("{'empName':'Dinesh Rajput', 'empAge': 26,'salary':70000}");
 
  collection.insert(dbObject);
 
  DBCursor cursorDoc = collection.find();
  while (cursorDoc.hasNext()) {
   System.out.println(cursorDoc.next());
  }
 
  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}
If everything is fine then we will get the following output on the console.
output:

{ "_id" : { "$oid" : "5106c6eb581d9921d6f5ccee"} , "empName" : "Dinesh Rajput" , "empAge" : 26 , "salary" : 70000}
Done


Download Source Code + Libs
MongoDBJSONDemo.Zip


                             <<previous<<             || index  ||         >>next>>


Java MongoDB Query a Document to Database

In this tutorial one Of the four basic database operations (i.e. CRUD), read operation are those that retrieve records or documents from a collection in MongoDB. For general information about read operations and the factors that affect their performance, see Read Operations; for documentation of the other CRUD operations.

You can retrieve documents from MongoDB using either of the following methods:
  • find
  • findOne

Find

The find() method is the primary method to select documents from a collection. The find() method returns a cursor that contains a number of documents. Most drivers provide application developers with a native iterable interface for handling cursors and accessing documents. The find() method has the following syntax:

db.collection.find( <query>, <projection> ) 
 
Corresponding Operation in SQL
The find() method is analogous to the SELECT statement, while:
  • the <query> argument corresponds to the WHERE statement, and
  • the <projection> argument corresponds to the list of fields to select from the result set.

Find One

The findOne() method selects and returns a single document from a collection and returns that document. findOne() does not return a cursor.

The findOne() method has the following syntax:
db.collection.findOne( <query>, <projection> ) 
 
Except for the return value, findOne() method is quite similar to the find() method; in fact, internally, the findOne() method is the find() method with a limit of 1.

Cursor

The find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable, then the cursor is automatically iterated up to 20 times  to print up to the first 20 documents that match the query, as in the following example:
db.bios.find( { _id: 1 } );
 Click here to know more about the Read Data and its options.

In Java MongoDB API, you can use collection.find() to get / query document from collection. Here is few common use cases :

For this example we have insert some document into the mongoDB "dineshonjavaDB"
as follows inserting 10 documents to the "employee" collection on mongoDB.
for (int i=10001; i <= 10010; i++) {
 collection.insert(new BasicDBObject().append("empId", i));
}
1. Fetch first record.
DBObject doc = collection.findOne(); //get first document
System.out.println(dbObject);
2. Get the set of document.
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
    System.out.println(cursor.next());
}
3. fetch documents where empId = 8.
BasicDBObject query = new BasicDBObject();
query.put("empId", 10008);
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
    System.out.println(cursor.next());
}
4. fetch documents where number = 10009 and 10010, use "$in" operator.
BasicDBObject query = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(10009);
list.add(10010);
query.put("empId", new BasicDBObject("$in", list));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
   System.out.println(cursor.next());
}
5. fetch documents where empId > 10003, use "$gt" operator.
BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$gt", 10003));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
 System.out.println(cursor.next());
}
6. fetch documents where 10002 < number < 10005, combine two operators, "$gt" and "$lt".
BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$gt", 10002).append("$lt", 10005));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
 System.out.println(cursor.next());
}

7. fetch documents where number != 10001, use "$ne" operator.
BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$ne", 10001));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()) {
  System.out.println(cursor.next());
}

Now lets see the full example and run this ..
package com.dineshonjava.mongo.test;

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.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * @author Dinesh Rajput
 *
 */
public class ReadDocumentDemo {

 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
 
  // get a single collection
  DBCollection collection = db.getCollection("employeesCollection");

  // insert empId 10001 to 10010 for testing
  for (int i = 10001; i <= 10010; i++) {
   collection.insert(new BasicDBObject().append("empId", i));
  }

  // get first document
  DBObject dbObject = collection.findOne();
  System.out.println(dbObject);
  System.out.println("*****************First Test*****************");
  // get all available documents
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
  System.out.println("*****************Second Test*****************");
  // get document, where empId = 10003
  BasicDBObject query = new BasicDBObject();
  query.put("empId", 10003);
  DBCursor cursor2 = collection.find(query);
  while (cursor2.hasNext()) {
   System.out.println(cursor2.next());
  }
  System.out.println("*****************Third Test*****************");
  // get document, where empId = 10002 and empId = 10004
  BasicDBObject query2 = new BasicDBObject();
  List<Integer> list = new ArrayList<Integer>();
  list.add(10002);
  list.add(10004);
  query2.put("empId", new BasicDBObject("$in", list));
  DBCursor cursor3 = collection.find(query2);
  while (cursor3.hasNext()) {
   System.out.println(cursor3.next());
  }
  System.out.println("*****************Fourth Test*****************");
  // get document, where empId > 10006
  BasicDBObject query3 = new BasicDBObject();
  query3.put("empId", new BasicDBObject("$gt", 10006));
  DBCursor cursor4 = collection.find(query3);
  while (cursor4.hasNext()) {
   System.out.println(cursor4.next());
  }
  System.out.println("*****************Fifth Test*****************");
  // get document, where 10005 < empId < 10007
  BasicDBObject query4 = new BasicDBObject();
  query4.put("empId", new BasicDBObject("$gt", 10005).append("$lt", 10007));
  DBCursor cursor5 = collection.find(query4);
  while (cursor5.hasNext()) {
   System.out.println(cursor5.next());
  }
  System.out.println("*****************Sixth Test*****************");
  // get document, where empId != 10008
  BasicDBObject query5 = new BasicDBObject();
  query5.put("empId", new BasicDBObject("$ne", 10008));
  DBCursor cursor6 = collection.find(query5);
  while (cursor6.hasNext()) {
   System.out.println(cursor6.next());
  }

  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}
If every thing is fine then run as Java Application we will get the following output on the console.
output: 
{ "_id" : { "$oid" : "5106c015c781b5829079a5da"} , "empId" : 10001}
 *****************First Test*****************
{ "_id" : { "$oid" : "5106c015c781b5829079a5da"} , "empId" : 10001}
 { "_id" : { "$oid" : "5106c015c781b5829079a5db"} , "empId" : 10002}
 { "_id" : { "$oid" : "5106c015c781b5829079a5dc"} , "empId" : 10003}
{ "_id" : { "$oid" : "5106c015c781b5829079a5dd"} , "empId" : 10004}
 { "_id" : { "$oid" : "5106c015c781b5829079a5de"} , "empId" : 10005}
 { "_id" : { "$oid" : "5106c015c781b5829079a5df"} , "empId" : 10006}
 { "_id" : { "$oid" : "5106c015c781b5829079a5e0"} , "empId" : 10007}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e1"} , "empId" : 10008}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e2"} , "empId" : 10009}
 { "_id" : { "$oid" : "5106c015c781b5829079a5e3"} , "empId" : 10010}
 *****************Second Test*****************
{ "_id" : { "$oid" : "5106c015c781b5829079a5dc"} , "empId" : 10003}
*****************Third Test*****************
 { "_id" : { "$oid" : "5106c015c781b5829079a5db"} , "empId" : 10002}
 { "_id" : { "$oid" : "5106c015c781b5829079a5dd"} , "empId" : 10004}
 *****************Fourth Test*****************
{ "_id" : { "$oid" : "5106c015c781b5829079a5e0"} , "empId" : 10007}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e1"} , "empId" : 10008}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e2"} , "empId" : 10009}
 { "_id" : { "$oid" : "5106c015c781b5829079a5e3"} , "empId" : 10010}
*****************Fifth Test*****************
 { "_id" : { "$oid" : "5106c015c781b5829079a5df"} , "empId" : 10006}
 *****************Sixth Test*****************
{ "_id" : { "$oid" : "5106c015c781b5829079a5da"} , "empId" : 10001}
 { "_id" : { "$oid" : "5106c015c781b5829079a5db"} , "empId" : 10002}
 { "_id" : { "$oid" : "5106c015c781b5829079a5dc"} , "empId" : 10003}
{ "_id" : { "$oid" : "5106c015c781b5829079a5dd"} , "empId" : 10004}
{ "_id" : { "$oid" : "5106c015c781b5829079a5de"} , "empId" : 10005}
{ "_id" : { "$oid" : "5106c015c781b5829079a5df"} , "empId" : 10006}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e0"} , "empId" : 10007}
{ "_id" : { "$oid" : "5106c015c781b5829079a5e2"} , "empId" : 10009}
 { "_id" : { "$oid" : "5106c015c781b5829079a5e3"} , "empId" : 10010}
Done

Download Source Code + Libs
MongoDBQueryDemo.zip

Reference

MongoDB operator documentation



                             <<previous<<             || index  ||         >>next>>



Java MongoDB Updating a Document to Database

In this tutorail we are going to discuss how to update data into a collection. Update can be done with update(). The update() takes four arguments - criteria, objectnew,upsert and multi.
criteria - Query which specify the record to update;
objectnew- Specify the updated information or it can be used by $ operator (i.e. $inc...).
upsert - An upsert do update the record if match the criteria and insert record if not match.
multi - This argument asks to updates all matching rows or just the first one(which is default).
Our database name is 'dineshonjavaDB' and our collection name is 'employee'. Here, inserting two more records.

The update() method is the primary method used to modify documents in a MongoDB collection. By default, the update() method updates a single document, but by using the multi option, update() can update all documents that match the query criteria in the collection. The update() method can either replace the existing document with the new document or update specific fields in the existing document.
The update() has the following syntax:
db.collection.update( <query>, <update>, <options> )
Corresponding operation in SQL
The update() method corresponds to the UPDATE operation in SQL, and:
  • the <query> argument corresponds to the WHERE statement, and
  • the <update> corresponds to the SET ... statement.
The default behavior of the update() method updates a single document and would correspond to the SQL UPDATE statement with the LIMIT 1. With the multi option, update() method would correspond to the SQL UPDATE statement without the LIMIT clause.

Click here to know more about the Update command and its options.

In Java MongoDB API, you can use collection.update() to update an existing document. Here is some common use cases :

1. A normal way to update an existing document.
Find empId = 10006, and update it with a new document.
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("empId", 10006);
newDocument.put("empName", "Dinesh Rajput");
newDocument.put("salary", 70000);
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

2. This example show the use of "$inc" modifier to increase a particular value.
Find empId = 10006, update the "salary" value by increasing its value from 70000 to 90000, (70000 + 20000) = 90000.
BasicDBObject newDocument = new BasicDBObject().append("$inc", 
new BasicDBObject().append("salary", 20000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

3. This example show the use of "$set" modifier to update a particular value.
Find empId = 10006, update the "salary" from 70000 to 90000.
BasicDBObject newDocument = new BasicDBObject().append("$set", 
 new BasicDBObject().append("salary", 90000));
 
collection.update(new BasicDBObject().append("empId", 10006), newDocument);

4. This example show the use of "multi" parameter to update a set of matched documents.
Find empAge= 26, update all the matched documents, "salary" value to 60000.
//find empAge= 26 , update all matched documents , "salary" value to 60000
BasicDBObject updateQuery = new BasicDBObject().append("$set", 
 new BasicDBObject().append("salary", "60000"));
 
//both methods are doing the same thing.
//collection.updateMulti(new BasicDBObject().append("empAge", "26"), updateQuery);
collection.update(new BasicDBObject().append("empAge", "26"), updateQuery, false, true);

See the full example and its output.

package com.dineshonjava.mongo.test;

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.MongoException;

/**
 * @author Dinesh Rajput
 *
 */
public class UpdateDocumentDemo {

 public static void printAllDocuments(DBCollection collection){
  DBCursor cursor = collection.find();
  while (cursor.hasNext()) {
   System.out.println(cursor.next());
  }
 }
 
 public static void removeAllDocuments(DBCollection collection){
  collection.remove(new BasicDBObject());
 }
 
 public static void insertDummyDocuments(DBCollection collection){
  BasicDBObject document = new BasicDBObject();
  document.put("empId", "10006");
  document.put("empName", "Dinesh");
  document.put("salary", 70000);
 
  BasicDBObject document2 = new BasicDBObject();
  document2.put("empId", "10007");
  document2.put("empName", "Sweety");
  document2.put("salary", 70000);
 
  BasicDBObject document3 = new BasicDBObject();
  document3.put("empId", "10008");
  document3.put("empName", "Dinesh");
  document3.put("salary", 60000);
 
  collection.insert(document);
  collection.insert(document2);
  collection.insert(document3);
 }
 
 public static void main(String[] args) {
 
 try {
 
  Mongo mongo = new Mongo("localhost", 27017);
  DB db = mongo.getDB("dineshonjavaDB");
 
  // get a single collection
  DBCollection collection = db.getCollection("employee");
 
  System.out.println("Testing 1...");
  insertDummyDocuments(collection);
  //find empId = 10006, and update it with new document
  BasicDBObject newDocument = new BasicDBObject();
  newDocument.put("empId", "10006");
  newDocument.put("empName", "Dinesh Rajput");
  newDocument.put("salary", 80000);
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 2...");
  insertDummyDocuments(collection);
  //find empId = 10006 and increase its "salary" value by 90000
  BasicDBObject newDocument2 = new BasicDBObject().append("$inc", 
    new BasicDBObject().append("salary", 20000));
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument2);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 3...");
  insertDummyDocuments(collection);
  //find empId = 10006 and update salary to from 70000 to 90000
  BasicDBObject newDocument3 = new BasicDBObject().append("$set", 
    new BasicDBObject().append("salary", 90000));
 
  collection.update(new BasicDBObject().append("empId", "10006"), newDocument3);
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Testing 4...");
  insertDummyDocuments(collection);
  //find empName = Dinesh , update all matched documents , salary value to 80000
  BasicDBObject updateQuery = new BasicDBObject().append("$set", 
    new BasicDBObject().append("salary", 80000));
 
  //both method are same
  //collection.updateMulti(new BasicDBObject().append("empName", "Dinesh"), updateQuery);
 
  collection.update(new BasicDBObject().append("empName", "Dinesh"), updateQuery, false, true);
 
  printAllDocuments(collection);
  removeAllDocuments(collection);
 
  System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}

if every thing fine then run as java application and see the follwing output on the console.
output:
Testing 1...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428bf"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c0"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428be"} , "empId" : "10006" , "empName" : "Dinesh Rajput" , "salary" : 80000}
Testing 2...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c1"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 90000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c2"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c3"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
Testing 3...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c4"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 90000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c5"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c6"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 60000}
Testing 4...
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c7"} , "empId" : "10006" , "empName" : "Dinesh" , "salary" : 80000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c8"} , "empId" : "10007" , "empName" : "Sweety" , "salary" : 70000}
{ "_id" : { "$oid" : "51055d6f8217d9c7d67428c9"} , "empId" : "10008" , "empName" : "Dinesh" , "salary" : 80000}
Done

References

  1. How to do updating in MongoDB
  2. Update modifiers operations in MongoDB
  3. Java MongoDB APIs , DBCollection.update()

Download Source Code + Libs
MongoDBUpdateDemo.zip

                             <<previous<<             || index  ||         >>next>>



Java MongoDB Deleting a Document to Database

Of the four basic database operations (i.e. CRUD), delete operations are those that remove documents from a collection in MongoDB. In Java MongoDB API, you can use collection.remove() to delete document from collection.

If we want to remove the document from the collection 'employees' which contains the empId "10001" the following mongodb command can be used :
>db.employees.remove( { "empId" : "10001" } )

Use the remove() method to delete documents from a collection. The remove() method has the following syntax:
db.collection.remove( <query>, <justOne> )
Corresponding operation in SQL
The remove() method is analogous to the DELETE statement, and:

the <query> argument corresponds to the WHERE statement, and
the <justOne> argument takes a Boolean and has the same affect as LIMIT 1.

remove() deletes documents from the collection. If you do not specify a query, remove() removes all documents from a collection, but does not remove the indexes.
If we want to remove all data from the collection 'employees' the following mongodb command can be used :
>db.employees.remove( { } )
For testing the Remove function first we insert 10 documents to employees collection
for (int i=1001; i <= 10010; i++) {
 collection.insert(new BasicDBObject().append("empId", i));
}
DBCollection.remove()- 1. Get first document and delete it. In this case, empId = 10001 is deleted.
DBObject doc = collection.findOne(); //get first document
collection.remove(doc);
2. Puts query data in a BasicDBObject object. In this case, empId = 10002 is deleted.
BasicDBObject document = new BasicDBObject();
document.put("empId", 10002);
collection.remove(document);
Query like this only delete empId= 3.
BasicDBObject document = new BasicDBObject();
 document.put("empId", 10002);
 document.put("empId", 10003); //override above value 10002
 collection.remove(document);
Nice try, but query like this will not work, it will delete NOTHING.
BasicDBObject document = new BasicDBObject();
 List<Integer> list = new ArrayList<Integer>();
 list.add(10007);
 list.add(10008);
 document.put("empId", list);
 collection.remove(document);
3. Use BasicDBObject directly. In this case, empId = 10002 is deleted.
collection.remove(new BasicDBObject().append("empId", 10002));
4. Puts a "greater than" operator in a BasicDBObject object. In this case, empId = 10003 is deleted.
BasicDBObject query = new BasicDBObject();
query.put("empId", new BasicDBObject("$gt", 10002));
collection.remove(query);
5. Puts a "in" operator in a BasicDBObject object, construct the query in ArrayList. In this case, empId = 10004 and empId = 10005 are deleted.
BasicDBObject query = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(10004);
list.add(10005);
query.put("number", new BasicDBObject("$in", list));
collection.remove(query);
6. Use cursor to delete all available document.
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
 collection.remove(cursor.next());
}
7. Pass an empty BasicDBObject, and cause it delete all available document.
collection.remove(new BasicDBObject());
More Conditional Operators-
$all-
$all selects the documents where the field holds an array and contains all elements (e.g. <value>, <value1>, etc.) in the array. Consider the following example:
db.inventory.find( { tags: { $all: [ "appliances", "school", "book" ] } } )
$lt- 
Syntax: {field: {$lt: value} } $lt selects the documents where the value of the field is less than (i.e. <) the specified value. Consider the following example:
db.inventory.find( { qty: { $lt: 20 } } )
This query will select all documents in the inventory collection where the qty field value is less than 20.

$gt-
Syntax: {field: {$gt: value} }
$gt selects those documents where the value of the field is greater than (i.e. >) the specified value.

Consider the following example:
db.inventory.find( { qty: { $gt: 20 } } )
This query will select all documents in the inventory collection where the qty field value is greater than 20.
Now lets see the full example on the following java file and its output.
package com.dineshonjava.mongo.test;

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.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * @author Dinesh Rajput
 *
 */
public class DeleteDocumentDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
 try {
  // connect to mongoDB, IP and port number
  Mongo mongo = new Mongo("localhost", 27017);
 
  // get database from MongoDB,
  // if database doesn't exists, mongoDB will create it automatically
  DB db = mongo.getDB("dineshonjavaDB");
   
  // get a single collection
  DBCollection collection = db.getCollection("employee");
 
  //insert empId 10001 to 10010 for testing
  for (int i=10001; i <= 10010; i++) {
  collection.insert(new BasicDBObject().append("empId", i));
  }
 
  //remove empId = 10001
  DBObject doc = collection.findOne(); //get first document
  collection.remove(doc);
 
  //remove empId = 10002
  BasicDBObject document = new BasicDBObject();
  document.put("empId", 10002);
  collection.remove(document);
 
  //remove empId = 10003
  collection.remove(new BasicDBObject().append("empId", 10003));
 
  //remove empId > 10009 , means delete empId = 10010
  BasicDBObject query = new BasicDBObject();
  query.put("empId", new BasicDBObject("$gt", 10009));
  collection.remove(query);
 
  //remove empId = 10004 and 10005
  BasicDBObject query2 = new BasicDBObject();
  List<Integer> list = new ArrayList<Integer>();
  list.add(10004);
  list.add(10005);
  query2.put("empId", new BasicDBObject("$in", list));
  collection.remove(query2);
 
  //remove all documents
  //DBCursor cursor = collection.find();
  //while (cursor.hasNext()) {
  // collection.remove(cursor.next());
  //}
 
  //remove all documents , no query means delete all
  //collection.remove(new BasicDBObject());
 
  //print out the document
  DBCursor cursor = collection.find();
            while(cursor.hasNext()) {
                 System.out.println(cursor.next());
            }
 
            System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}
If everything is fine then run as a java application and you will get the following output on the console.
output:
{ "_id" : { "$oid" : "51054d998217798d9fc43545"} , "empId" : 10006}
{ "_id" : { "$oid" : "51054d998217798d9fc43546"} , "empId" : 10007}
{ "_id" : { "$oid" : "51054d998217798d9fc43547"} , "empId" : 10008}
{ "_id" : { "$oid" : "51054d998217798d9fc43548"} , "empId" : 10009}
Done



Reference-

MongoDB Advance Queries


Download Source Code + Libs
MongoDBDeleteDemo.zip

                             <<previous<<             || index  ||         >>next>>

Java MongoDB Inserting a Document to Database

In this tutorial we will discussing about inserting a document to the MongoDB. There are four ways to inserting document JSON format to the MongoDB. Here in this page we are going to discuss how to insert data into a collection. The documents stored in MongoDB are JSON-like. All data stored into the collection are in BSON format.

Switch to a MongoDB database-
Here, our database is "dineshonjavaDB".

> use dineshonjavaDB
switch to db dineshonjavaDB

1. Define a document for MongoDB database-
The following document can be stored in MongoDB.
> document=({"empId" : "10001","empName" :"Dinesh Rajput" ,"date_of_join" : "10/04/2010"
 ,"education" :"M.C.A." , "profession" : "DEVELOPER","interest" : "MUSIC","community_name"
 :["MODERN MUSIC", "CLASSICAL MUSIC","WESTERN MUSIC"],"community_moder_id" : ["MR. BBB","MR.
 JJJ","MR MMM"],"community_members" : [500,200,1500],"friends_id" : 
["MMM123","NNN123","OOO123"],"ban_friends_id" :["BAN123","BAN456","BAN789"]});
Java MongoDB Inserting a Document to Database

2. DBCollection.insert()- Insert a document into a collection-
To save the above document into the collection "employees" under "dineshonjavaDB" database the following command can be used -
> db.employees.insert(document) 
MongoDB Inserting a Document to Database

There are 4 Ways to insert data into MongoDB using Java API.

1. BasicDBObject example
BasicDBObject document = new BasicDBObject();
document.put("database", "dineshonjavaDB");
document.put("table", "employees");
 
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("empId", "10001");
documentDetail.put("empName", "Dinesh");
documentDetail.put("salary", "70000");
 
document.put("detail", documentDetail);
 
collection.insert(document);
2. BasicDBObjectBuilder example
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  .add("database", "dineshonjavaDB")
  .add("table", "employees");
 
 BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
 .add("empId", "10001")
 .add("empName", "Dinesh")
 .add("salary", "70000");
 
 documentBuilder.add("detail", documentBuilderDetail.get());
 
 collection.insert(documentBuilder.get());
  • Create a new BasicDBObject and invoke its put() method to set the document attributes.
  • Create a BasicDBObjectBuilder instance (that follows the builder design pattern) by invoking the static BasicDBObjectBuilder.start() method, calling the add() method to add attributes to the document, and then invoking get() to retrieve the resultant DBObject, which is the approach I took when building the employees document

3. Map example
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("database", "dineshonjavaDB");
documentMap.put("table", "employees");
 
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("empId", "10001");
documentMapDetail.put("empName", "Dinesh");
documentMapDetail.put("salary", "70000");

documentMap.put("detail", documentMapDetail);
 
collection.insert(new BasicDBObject(documentMap));
4. JSON parse example
String json = "{'database' : 'dineshonjavaDB','table' : 'employees'," +
 "'detail' : {'empId' : 10001, 'empName' : 'Dinesh', 'salary' : 70000}}}";

DBObject dbObject = (DBObject)JSON.parse(json);
 
collection.insert(dbObject);

Now see the full example of Inserting data into the collection
package com.dineshonjava.mongo.test;

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.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * @author Dinesh Rajput
 *
 */
public class InsertDocumentDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
 try {
  // connect to mongoDB, IP and port number
  Mongo mongo = new Mongo("localhost", 27017);
  // get database from MongoDB,
  // if database doesn't exists, mongoDB will create it automatically
  DB db = mongo.getDB("dineshonjavaDB");
   
  // get a single collection
  DBCollection collection = db.getCollection("employees");

  // BasicDBObject example
  System.out.println("BasicDBObject example...");
  BasicDBObject document = new BasicDBObject();
  document.put("database", "dineshonjavaDB");
  document.put("table", "employees");

  BasicDBObject documentDetail = new BasicDBObject();
  documentDetail.put("empId", "10001");
  documentDetail.put("empName", "Dinesh");
  documentDetail.put("salary", "70000");
  document.put("detail", documentDetail);

  collection.insert(document);

  DBCursor cursorDoc = collection.find();
  while (cursorDoc.hasNext()) {
  System.out.println(cursorDoc.next());
  }
 
  collection.remove(new BasicDBObject());

  // BasicDBObjectBuilder example
  System.out.println("BasicDBObjectBuilder example...");
 BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
   .add("database", "dineshonjavaDB")
                        .add("table", "employees");
 
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
                    .add("empId", "10001")
                    .add("empName", "Dinesh")
           .add("salary", "70000");
 
 documentBuilder.add("detail", documentBuilderDetail.get());
 
 collection.insert(documentBuilder.get());
 
 DBCursor cursorDocBuilder = collection.find();
 while (cursorDocBuilder.hasNext()) {
  System.out.println(cursorDocBuilder.next());
 }
 
 collection.remove(new BasicDBObject());
 
 // Map example
 System.out.println("Map example...");
 Map<String, Object> documentMap = new HashMap<String, Object>();
 documentMap.put("database", "dineshonjavaDB");
 documentMap.put("table", "employees");
 
 Map<String, Object> documentMapDetail = new HashMap<String, Object>();
 documentMapDetail.put("empId", "10001");
 documentMapDetail.put("empName", "Dinesh");
 documentMapDetail.put("salary", "70000");
 
 documentMap.put("detail", documentMapDetail);
 
 collection.insert(new BasicDBObject(documentMap));
 
 DBCursor cursorDocMap = collection.find();
 while (cursorDocMap.hasNext()) {
  System.out.println(cursorDocMap.next());
 }
 
 collection.remove(new BasicDBObject());
 
 // JSON parse example
 System.out.println("JSON parse example...");
 
 String json = "{'database' : 'dineshonjavaDB','table' : 'employees'," +
 "'detail' : {'empId' : 10001, 'empName' : 'Dinesh', 'salary' : '70000'}}}";
 
 DBObject dbObject = (DBObject)JSON.parse(json);
 
 collection.insert(dbObject);
 
 DBCursor cursorDocJSON = collection.find();
 while (cursorDocJSON.hasNext()) {
  System.out.println(cursorDocJSON.next());
 }
 
 //collection.remove(new BasicDBObject());
 
 System.out.println("Done");
 
} catch (UnknownHostException e) {
   e.printStackTrace();
} catch (MongoException e) {
   e.printStackTrace();
}
 
}

}

If every thing is fine then run as Java Application then we will get the following output on the console.
output:
BasicDBObject example...
{ "_id" : { "$oid" : "5104d7cc37de7e0a362e84ae"} , "database" : "dineshonjavaDB" , "table" : "employees" , "detail" : { "empId" : "10001" , "empName" : "Dinesh" , "salary" : "70000"}}
BasicDBObjectBuilder example...
{ "_id" : { "$oid" : "5104d7cc37de7e0a362e84af"} , "database" : "dineshonjavaDB" , "table" : "employees" , "detail" : { "empId" : "10001" , "empName" : "Dinesh" , "salary" : "70000"}}
Map example...
{ "_id" : { "$oid" : "5104d7cc37de7e0a362e84b0"} , "detail" : { "empName" : "Dinesh" , "empId" : "10001" , "salary" : "70000"} , "table" : "employees" , "database" : "dineshonjavaDB"}
JSON parse example...
{ "_id" : { "$oid" : "5104d7cc37de7e0a362e84b1"} , "database" : "dineshonjavaDB" , "table" : "employees" , "detail" : { "empId" : 10001 , "empName" : "Dinesh" , "salary" : "70000"}}
Done

What is "_id" ?
 The "_id" is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with "_", "/" and "$" are reserved for internal use.

Reference
Java tutorial – MongoDB

Download Source Code + Libs
MongoDBInsertDocumentDemo.zip


                             <<previous<<             || index  ||         >>next>>




Java MongoDB Get Collection from Database

In this tutorial we will discuss an example of java which describe how to get the collection from MongoDb and other functions of collection.

To get a collection to use, just specify the name of the collection to the getCollection(String collectionName) method:
DBCollection coll = db.getCollection("dineshonjavaCollection");
Once you have this collection object, you can now do things like insert data, query for data, etc. Suppose "dineshonjavaCollection" if this collection already created not created on the mongoDB then return the "dineshonjavaCollection" else it create new "dineshonjavaCollection" in the MongoDB.

com.mongodb.DBCollection is abstract class. This class provides a skeleton implementation of a database collection.
A typical invocation sequence is thus
Mongo mongo = new Mongo( new DBAddress( "localhost", 127017 ) );
     DB db = mongo.getDB( "dineshonjavaDB" );
     DBCollection collection = db.getCollection( "dineshonjavaCollection" );
If you do not know the collection name, use db.getCollectionNames() to get the entire list of collection names from a selected database.
DB db = mongo.getDB("dineshonjavaDB");
Set<String> collections = db.getCollectionNames();
 
for (String collectionName : collections) {
   System.out.println(collectionName);
}
If "dineshonjavaDB" contains collection name "dineshonjavaCollection", then you will see following result :

system.indexes //system collection
system.users //system collection
dineshonjavaCollection

Full example to get collection from MongoDB, via Java driver.
package com.dineshonjava.mongo.test;

import java.net.UnknownHostException;
import java.util.Set;

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

/**
 * @author Dinesh Rajput
 *
 */
public class CollectiomDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
   // connect to mongoDB, IP and port number
   Mongo mongo = new Mongo("localhost", 27017);
 
   // get database from MongoDB,
   // if database doesn't exists, mongoDB will create it automatically
   DB db = mongo.getDB("dineshonjavaDB");
 
   // get list of collections
   Set<String>collections = db.getCollectionNames();
 
   for (String collectionName : collections) {
    System.out.println(collectionName);
   }
   System.out.println("************************************************");   
   // Get collection from MongoDB, database named "dineshonjavaDB"
   // if collection doesn't exists, mongoDB will create it automatically
   DBCollection collection = db.getCollection("dineshonjavaCollection");
 
   System.out.println(collection);
 
   System.out.println("Done");
 
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (MongoException e) {
   e.printStackTrace();
  }
 
 }

}

If every thing is fine then run as a java application then we will get following output on console.
output:
dineshonjavaCollection
employees
system.indexes
************************************************
dineshonjavaCollection
Done

Reference
Java tutorial – MongoDB

Download Source Code + Libs
MongoDBCollectionDemo.zip

                             <<previous<<             || index  ||         >>next>>