BasicDBObject
query = new BasicDBObject();
List<Integer>
list = new ArrayList<Integer> ();
list.add(2);
list.add(4);
query.put("_id",
new BasicDBObject("$in", list));
WriteResult
result = collection.remove(query);
Above
snippet removes documents where “_id” is 2 or 4.
import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; 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()); } BasicDBObject query = new BasicDBObject(); List<Integer> list = new ArrayList<Integer> (); list.add(2); list.add(4); query.put("_id", new BasicDBObject("$in", list)); WriteResult result = collection.remove(query); 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" : 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" : 3.0 , "firstName" : "Gopi" , "lastName" : "Battu" , "salary" : 30000.0} { "_id" : 5.0 , "firstName" : "Anand" , "lastName" : "Bandaru" , "designation" : "Project Manager" , "salary" : 30000.0} Result is : { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 2}
No comments:
Post a Comment