<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">
<div dir="ltr" style="text-align: left;">In this tutorial we will discuss about the deleting the document from mongoDB. Document is same as a row in the table of relational database. In the our example we will fire deleting a document from &#8220;dojCollection&#8221; of &#8220;dineshonjavaDB&#8221;.</p>
<h2><b>Methods for removing documents-</b></h2>
<p>You can use several overloaded methods to remove an object from the database.</p>
<div class="itemizedlist">
<ul >
<li><b>remove</b> Remove the given document based on one of the following: a specific object instance, a query document criteria combined with a class or a query document criteria combined with a specific collection name.</li>
</ul>
</div>
<p>To see the more about the deleting plesse click on <a href="https://dineshonjava.com/java-mongodb-deleting-document-to/" target="_blank" rel="noopener"><b>MongoDB Deleting a Document to Database</b></a></p>
<p>In Spring data for MongoDB, you can use <b>remove()</b> and <b>findAndRemove()</b> to delete document from mongoDB.</p>
</div>
<pre class="highlight">Employee employee = new Employee(); 
 
 //delete employee object, under entity collection ("dojCollection") 
 mongoOperation.remove(employee); 
 
 //delete where empId = 10002, under "dojCollection" collection 
 mongoOperation.remove(new Query(Criteria.where("empId").is(10002)),"dojCollection"); 
 
 //delete where empId = 10003, under "dojCollection" collection 
 //and return the deleted employee object 
 Employee deletedEmployee = 
mongoOperation.findAndRemove(new Query(Criteria.where("empId").is(10003)), Employee.class,"dojCollection"); 
</pre>
<p><b><br />
</b> <b>Note:</b><br />
1. The findAndRemove() method will delete the matched record and return the deleted records.<br />
2. Be careful about the remove() method, if Query parameter failed to match any of the records, it will caused null pointer exception.</p>
<p>See the full example to query a document from the &#8220;<b>dojCollection</b>&#8221; of the &#8220;<b>dineshonjavaDB</b>&#8221;</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/02/springdelete.png" border="0" /></div>
<h3><b>Step 1: Creating the domain class Employee</b><br />
<b>Employee.java </b></h3>
</div>
<pre class="highlight">package com.dineshonjava.mongo.dto; 
 
import org.springframework.data.annotation.Id; 
import org.springframework.data.mongodb.core.mapping.Document; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
@Document 
public class Employee { 
 @Id 
 private int empId; 
 private String empName; 
 private long salary; 
 private int empAge; 
 public int getEmpId() { 
 return empId; 
 } 
 public void setEmpId(int empId) { 
 this.empId = empId; 
 } 
 public String getEmpName() { 
 return empName; 
 } 
 public void setEmpName(String empName) { 
 this.empName = empName; 
 } 
 public long getSalary() { 
 return salary; 
 } 
 public void setSalary(long salary) { 
 this.salary = salary; 
 } 
 public int getEmpAge() { 
 return empAge; 
 } 
 public void setEmpAge(int empAge) { 
 this.empAge = empAge; 
 } 
 @Override 
 public String toString() { 
 return "Employee [age=" + empAge + ", empName=" + empName + ", empId=" 
 + empId + ", salary=" + salary + "]"; 
 } 
} 
</pre>
<h3><b>Step 2: Creating configuration file<br />
mongo-config.xml</b></h3>
</div>
<pre class="highlight"><;beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/data/mongo 
 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">; 
 
 <;!-- Default bean name is 'mongo' -->; 
 <;mongo:mongo host="localhost" port="27017"/>; 
 <;!-- Default bean name is 'mongo' -->; 
 <;mongo:mongo>; 
 <;mongo:options connections-per-host="100" 
 threads-allowed-to-block-for-connection-multiplier="5" 
 max-wait-time="120000000" 
 connect-timeout="10000000" 
 socket-keep-alive="true" 
 socket-timeout="15000000" 
 auto-connect-retry="true"/>; 
 <;/mongo:mongo>; 
 
 <;context:annotation-config/>; 
 
 <;context:component-scan base-package="com.dineshonjava.mongo">; 
 <;context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>; 
 <;/context:component-scan>; 
 
 <;!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. -->; 
 <;bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">; 
 <;constructor-arg ref="mongo"/>; 
 <;constructor-arg name="databaseName" value="dineshonjavaDB"/>; 
 <;/bean>; 
 
</pre>
</div>
</div>
</div>
</div>
</div>
<h3><b>Step 3: Creating Class which inserting the document into the mongoDB.</b><br />
<b>HelloMongoDB.java</b></h3>
<pre class="highlight">package com.dineshonjava.mongo.main; 
 
import static org.springframework.data.mongodb.core.query.Criteria.where; 
import static org.springframework.data.mongodb.core.query.Query.query; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.data.mongodb.core.MongoOperations; 
import org.springframework.data.mongodb.core.query.Update; 
import org.springframework.stereotype.Repository; 
 
import com.dineshonjava.mongo.dto.Employee; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
@Repository 
public class HelloMongoDB { 
 
 @Autowired 
 MongoOperations mongoOperations; 
 
 public void execute() { 
 if (mongoOperations.collectionExists("dojCollection")) { 
 mongoOperations.dropCollection("dojCollection"); 
 } 
 Employee employee3 = new Employee(); 
 employee3.setEmpId(1001); 
 employee3.setEmpName("Dinesh Rajput"); 
 employee3.setSalary(70000); 
 employee3.setEmpAge(26); 
 
 Employee employee4 = new Employee(); 
 employee4.setEmpId(1002); 
 employee4.setEmpName("Adesh Rajput"); 
 employee4.setSalary(30000); 
 employee4.setEmpAge(23); 
 
 Employee employee5 = new Employee(); 
 employee5.setEmpId(1003); 
 employee5.setEmpName("Vinesh Rajput"); 
 employee5.setSalary(32000); 
 employee5.setEmpAge(23); 
 
 Employee employee6 = new Employee(); 
 employee6.setEmpId(1004); 
 employee6.setEmpName("Sweety Rajput"); 
 employee6.setSalary(50000); 
 employee6.setEmpAge(22); 
 
 List<;Employee>; empList = new ArrayList<;Employee>;(); 
 empList.add(employee3); 
 empList.add(employee4); 
 empList.add(employee5); 
 empList.add(employee6); 
 
 mongoOperations.insert(empList, "dojCollection"); 
 
 System.out.println("***********************CASE 1************************"); 
 // Case 1 ...delete where empId = 1001 
 // delete 
 mongoOperations.remove(query(where("empId").is(1001)), "dojCollection"); 
 System.out.println("deleted"); 
 System.out.println("***********************CASE 2**findAndRemove User*********************"); 
 // Case 2 ... delete where empId = 10002, and returns the deleted record 
 // find 
 Employee employee2 = mongoOperations.findAndRemove(query(where("empId").is(1002)), Employee.class,"dojCollection"); 
 System.out.println(employee2); 
 
 } 
} 
</pre>
<h3><b>Step 4: Running the Example</b></h3>
<p>Following code shows how to run this example</p>
<p><b>HelloMongoTestApp.java</b></p>
<pre class="highlight">package com.dineshonjava.mongo.main; 
 
import org.springframework.context.ConfigurableApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
public class HelloMongoTestApp { 
 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
 ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("mongo-config.xml"); 
 
 HelloMongoDB hello = (HelloMongoDB) context.getBean("helloMongoDB"); 
 hello.execute(); 
 System.out.println( "DONE!" ); 
 } 
 
} 
</pre>
<p>If everything is fine then run the above main application as Java Application we will get the following</p>
<div style="background-color: #ff99cc;"><b>output:</b><br />
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).<br />
log4j:WARN Please initialize the log4j system properly.<br />
***********************CASE 1************************<br />
deleted<br />
***********************CASE 2**findAndRemove User*********************<br />
Employee [age=23, empName=Adesh Rajput, empId=1002, salary=30000]<br />
DONE!</div>
<h2><b><br />
</b> <b>Download SourceCode+Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBSpringDeleteDemo.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>MongoDBSpringDeleteDemo.zip</b></a></h2>
<p><b>References</b><br />
<a href="http://static.springsource.org/spring-data/data-document/docs/1.0.0.M2/reference/html/#mongodb-template-query" target="_blank" rel="noopener"><b>MongoDB template query documentation</b></a></p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/spring-data-mongodb-query-document/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/spring-data-mongodb-delete-document/">next</a>>;>;</b></div>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-query-document/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-tutorial/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '580'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…