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

Previous
Next