Thursday, March 15, 2012

Spring data MongoDB CRUD operations


The existing documents available at the MongoDB documentation page does not provide a clear cut information about the CRUD operations.
Also ,they do not talk about the  limitations and their workaround, I thought writing below about the CRUD operation using SpringData + MongoDB .
Here we are going to do CRUD operation using SpringData + Mongo DB.

Consider a sample example, we have an Employee document. Employee can have multiple addresses:

 We want to do CRUD operation.And more specifically it's embedded documents which is a List.

@Document(collection = "employee_master")
public class Employee implements Serializable
{

    private static final long                serialVersionUID    = 1L;

    @Id
    private String                            employeeId;

    private List<EmployeeAddresses>    employeeAddresses;
    .....................
   
    ..............
    //
    MongoOperations references
    MongoOperations mongoOperations;       
   
    Creating Employee Address:
       Query query = new Query( Criteria.where( "employeeId" ).is( employeeId ) );
        Update update = new Update().push( "employeeAddresses" , employeeAddresse );
        mongoOperations.updateFirst( query , update , Employee.class );
           
    Updating Employee Address:
         Query query = new Query( Criteria.where( "employeeId" ).is( employeeId ) );
        Update update = new Update().set( "employeeAddresses.$.city" , "Sidney" );
       //  Please    note that we are using $ sign for the list attributes.
        mongoOperations.updateFirst( query , update ,"employee_master");
       
   
    Reading Employee Address:
       Note that Mongo DB does not support Projection. So You need to load the complete document Employee.
   
        Query query = new Query( Criteria.where( "employeeId" ).is( employeeId ) );
        Employee eployee = ( Employee ) findOne( query , Employee.class );
        List<EmployeeAddresses>    employeeAddresses = employee.getAddresses();
              
    Deleting  Employee Address:
    Mongo DB does not allow removal of a specific field. Please note that you can only remove an entire document.  This is similar to RDBMS, you can't remove a column for
    a  specific row/ record. Right!.
   
    Query query = new Query( Criteria.where( "employeeId" ).is( employeeId ) );
    mongoOperations.remove( query, Employee.class );

Hope the above is going to help us in using MongoDB more efficiently.

       

No comments:

Post a Comment