Categories: MongoDB

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

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago