Friday 6 March 2015

mongoDB : Java : Delete documents


Collection remove method is used to remove documents.

Remove first document in the collection
Step 1: Get the first document
DBObject obj = collection.findOne();

Step 2: Remove the document from collection
collection.remove(obj);

import java.net.UnknownHostException;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.WriteResult;

public class UpdateDocument {

  /* Step 1 : get mongoClient */
  public static MongoClient getMongoClient(){
    MongoClient mongoClient = null;
     try {
       mongoClient = new MongoClient( "localhost" , 27017 );
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
     return mongoClient;
  }
  
  public static void main(String args[]){
    MongoClient mongoClient = getMongoClient();
    
    /* Step 2: Connect to DB */
    DB db = mongoClient.getDB("sample");
    
    /*Step 3 : Get collection */
    DBCollection collection = db.getCollection("employee");
    
    System.out.println("Before deleting");
    DBCursor cursor = collection.find();
    while(cursor.hasNext()){
      System.out.println(cursor.next());
    }
    
    DBObject obj = collection.findOne();
    WriteResult result = collection.remove(obj);
    
    System.out.println("After deleting");
    cursor = collection.find();
    while(cursor.hasNext()){
      System.out.println(cursor.next());
    }
    
    System.out.println("Result is : " + result);
  }
  
}


Output
Before deleting
{ "_id" : 1.0 , "firstName" : "Jessi" , "lastName" : "chelli" , "designation" : "Software Engineer" , "salary" : 55000.0}
{ "_id" : 2.0 , "firstName" : "Anand" , "lastName" : "Bandaru" , "salary" : 50000.0}
{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu" , "salary" : 30000.0}
{ "_id" : 4.0 , "firstName" : "Ritwik" , "lastName" : "Mohenthy" , "salary" : 30000.0}
{ "_id" : 5.0 , "firstName" : "Anand" , "lastName" : "Bandaru" , "designation" : "Project Manager" , "salary" : 30000.0}
After deleting
{ "_id" : 2.0 , "firstName" : "Anand" , "lastName" : "Bandaru" , "salary" : 50000.0}
{ "_id" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu" , "salary" : 30000.0}
{ "_id" : 4.0 , "firstName" : "Ritwik" , "lastName" : "Mohenthy" , "salary" : 30000.0}
{ "_id" : 5.0 , "firstName" : "Anand" , "lastName" : "Bandaru" , "designation" : "Project Manager" , "salary" : 30000.0}
Result is : { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 1}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment