Java MongoDB Deleting a Document to Database

Posted: August 5, 2014 in MongoDB
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 :

  1. >db.employees.remove( { “empId” : “10001” } )

Use the remove() method to delete documents from a collection. The remove() method has the following syntax:

  1. 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 :

  1. >db.employees.remove( { } )

For testing the Remove function first we insert 10 documents to employees collection

  1. for (int i=1001; i <= 10010; i++) {
  2.  collection.insert(new BasicDBObject().append(“empId”, i));
  3. }

DBCollection.remove()- 1. Get first document and delete it. In this case, empId = 10001 is deleted.

  1. DBObject doc = collection.findOne(); //get first document
  2. collection.remove(doc);

2. Puts query data in a BasicDBObject object. In this case, empId = 10002 is deleted.

  1. BasicDBObject document = new BasicDBObject();
  2. document.put(“empId”10002);
  3. collection.remove(document);

Query like this only delete empId= 3.

  1. BasicDBObject document = new BasicDBObject();
  2.  document.put(“empId”10002);
  3.  document.put(“empId”10003); //override above value 10002
  4.  collection.remove(document);

Nice try, but query like this will not work, it will delete NOTHING.

  1. BasicDBObject document = new BasicDBObject();
  2.  List<Integer> list = new ArrayList<Integer>();
  3.  list.add(10007);
  4.  list.add(10008);
  5.  document.put(“empId”, list);
  6.  collection.remove(document);

3. Use BasicDBObject directly. In this case, empId = 10002 is deleted.

  1. collection.remove(new BasicDBObject().append(“empId”10002));

4. Puts a “greater than” operator in a BasicDBObject object. In this case, empId = 10003 is deleted.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”new BasicDBObject(“$gt”10002));
  3. 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.

  1. BasicDBObject query = new BasicDBObject();
  2. List<Integer> list = new ArrayList<Integer>();
  3. list.add(10004);
  4. list.add(10005);
  5. query.put(“number”new BasicDBObject(“$in”, list));
  6. collection.remove(query);

6. Use cursor to delete all available document.

  1. DBCursor cursor = collection.find();
  2. while (cursor.hasNext()) {
  3.  collection.remove(cursor.next());
  4. }

7. Pass an empty BasicDBObject, and cause it delete all available document.

  1. 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:

  1. 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:

  1. 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:

  1. 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.

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.DB;
  7. import com.mongodb.DBCollection;
  8. import com.mongodb.DBCursor;
  9. import com.mongodb.DBObject;
  10. import com.mongodb.Mongo;
  11. import com.mongodb.MongoException;
  12. /**
  13.  * @author Dinesh Rajput
  14.  *
  15.  */
  16. public class DeleteDocumentDemo {
  17.  /**
  18.   * @param args
  19.   */
  20.  public static void main(String[] args) {
  21.  try {
  22.   // connect to mongoDB, IP and port number
  23.   Mongo mongo = new Mongo(“localhost”27017);
  24.   // get database from MongoDB,
  25.   // if database doesn’t exists, mongoDB will create it automatically
  26.   DB db = mongo.getDB(“dineshonjavaDB”);
  27.   // get a single collection
  28.   DBCollection collection = db.getCollection(“employee”);
  29.   //insert empId 10001 to 10010 for testing
  30.   for (int i=10001; i <= 10010; i++) {
  31.   collection.insert(new BasicDBObject().append(“empId”, i));
  32.   }
  33.   //remove empId = 10001
  34.   DBObject doc = collection.findOne(); //get first document
  35.   collection.remove(doc);
  36.   //remove empId = 10002
  37.   BasicDBObject document = new BasicDBObject();
  38.   document.put(“empId”10002);
  39.   collection.remove(document);
  40.   //remove empId = 10003
  41.   collection.remove(new BasicDBObject().append(“empId”10003));
  42.   //remove empId > 10009 , means delete empId = 10010
  43.   BasicDBObject query = new BasicDBObject();
  44.   query.put(“empId”new BasicDBObject(“$gt”10009));
  45.   collection.remove(query);
  46.   //remove empId = 10004 and 10005
  47.   BasicDBObject query2 = new BasicDBObject();
  48.   List<Integer> list = new ArrayList<Integer>();
  49.   list.add(10004);
  50.   list.add(10005);
  51.   query2.put(“empId”new BasicDBObject(“$in”, list));
  52.   collection.remove(query2);
  53.   //remove all documents
  54.   //DBCursor cursor = collection.find();
  55.   //while (cursor.hasNext()) {
  56.   // collection.remove(cursor.next());
  57.   //}
  58.   //remove all documents , no query means delete all
  59.   //collection.remove(new BasicDBObject());
  60.   //print out the document
  61.   DBCursor cursor = collection.find();
  62.             while(cursor.hasNext()) {
  63.                  System.out.println(cursor.next());
  64.             }
  65.             System.out.println(“Done”);
  66.   } catch (UnknownHostException e) {
  67.    e.printStackTrace();
  68.   } catch (MongoException e) {
  69.    e.printStackTrace();
  70.   }
  71.  }
  72. }

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

 

Leave a comment