<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">
<div dir="ltr" style="text-align: justify;">In this tutorial we will discuss about the querying the document to the mongoDB. Document is same as a row in the table of relational database. In the our example we will fire query ti access a document from &#8220;<b>dojCollection</b>&#8221; of &#8220;<b>dineshonjavaDB</b>&#8220;.<b>Querying Documents-</b></div>
<div dir="ltr"></div>
<div dir="ltr" style="text-align: justify;">
<p>You can express your queries using the <i><b>Query </b></i>and <b><i>Criteria </i></b>classes which have method names that mirror the native <b>MongoDB </b>operator names such as <b>lt, lte, is, and others</b>. The <i><b>Query </b></i>and <i><b>Criteria </b></i>classes follow a fluent API style so that you can easily chain together multiple method criteria and queries while having easy to understand code. Static imports in Java are used to help remove the need to see the &#8216;new&#8217; keyword for creating <i><b>Query </b></i>and <b><i>Criteria </i></b>instances so as to improve readability.</p>
<h3 style="text-align: left;"><b>1. Querying documents in a collection-</b></h3>
<p>We saw how to retrieve a single document using the <i><b>findOne </b></i>and <i><b>findById </b></i>methods on <b>MongoTemplate </b>in previous sections which return a single domain object. We can also query for a collection of documents to be returned as a list of domain objects. Assuming that we have a number of Person objects with name and age stored as documents in a collection and that each person has an embedded account document with a balance. We can now run a query using the following code.</p>
<p><b>For Example-</b></p>
</div>
<pre class="highlight">import static org.springframework.data.mongodb.core.query.Criteria.where; 
import static org.springframework.data.mongodb.core.query.Query.query; 
 ... 
List<;Employee>; result = 
mongoTemplate.find(query(where("age").lt(50).and("salary").gt(50000)) 
,Employee.class); 
</pre>
<p>All find methods take a Query object as a parameter. This object defines the criteria and options used to perform the query. The criteria is specified using a Criteria object that has a static factory method named where used to instantiate a new Criteria object. We recommend using a static import for <i><b>org.springframework.data.mongodb.core.query.Criteria.where</b></i> and <b><i>Query.query</i></b> to make the query more readable.</p>
<p>This query should return a list of Employee objects that meet the specified criteria. The Criteria class has the following methods that correspond to the operators provided in MongoDB.</p>
<p>As you can see most methods return the Criteria object to provide a fluent style for the API.</p>
<h3 class="title">Methods for the Criteria class</h3>
<div class="itemizedlist">
<ul >
<li>Criteria <b>all </b> (Object o)Creates a criterion using the $all operator</li>
<li>Criteria <b>and </b> (String key) Adds a chained Criteria with the specified key to the current Criteria and retuns the newly created one</li>
<li>Criteria <b>andOperator </b> (Criteria&#8230; criteria)Creates an and query using the $and operator for all of the provided criteria (requires MongoDB 2.0 or later)</li>
<li>Criteria <b>elemMatch </b> (Criteria c) Creates a criterion using the $elemMatch operator</li>
<li>Criteria <b>exists </b> (boolean b) Creates a criterion using the $exists operator</li>
<li>Criteria <b>gt </b> (Object o)Creates a criterion using the $gt operator</li>
<li>Criteria <b>gte </b> (Object o)Creates a criterion using the $gte operator</li>
<li>Criteria <b>in </b> (Object&#8230; o) Creates a criterion using the $in operator for a varargs argument.</li>
<li>Criteria <b>in </b> (Collection<;?>; collection) Creates a criterion using the $in operator using a collection</li>
<li>Criteria <b>is </b> (Object o)Creates a criterion using the $is operator</li>
<li>Criteria <b>lt </b> (Object o)Creates a criterion using the $lt operator</li>
<li>Criteria <b>lte </b> (Object o)Creates a criterion using the $lte operator</li>
<li>Criteria <b>mod </b> (Number value, Number remainder)Creates a criterion using the $mod operator</li>
<li>Criteria <b>ne </b> (Object o)Creates a criterion using the $ne operator</li>
<li>Criteria <b>nin </b> (Object&#8230; o) Creates a criterion using the $nin operator</li>
<li>Criteria <b>norOperator </b> (Criteria&#8230; criteria)Creates an nor query using the $nor operator for all of the provided criteria</li>
<li>Criteria <b>not </b> ()Creates a criterion using the $not meta operator which affects the clause directly following</li>
<li>Criteria <b>orOperator </b> (Criteria&#8230; criteria)Creates an or query using the $or operator for all of the provided criteria</li>
<li>Criteria <b>regex </b> (String re) Creates a criterion using a $regex</li>
<li>Criteria <b>size </b> (int s)Creates a criterion using the $size operator</li>
<li>Criteria <b>type </b> (int t)Creates a criterion using the $type operator</li>
</ul>
</div>
<div id="ads-id" align="center"></div>
<h3 class="title">Methods for the Query class</h3>
<div class="itemizedlist">
<ul >
<li>Query <b>addCriteria </b> (Criteria criteria) used to add additional criteria to the query</li>
<li>Field <b>fields </b> () used to define fields to be included in the query results</li>
<li>Query <b>limit </b> (int limit) used to limit the size of the returned results to the provided limit (used for paging)</li>
<li>Query <b>skip </b> (int skip) used to skip the provided number of documents in the results (used for paging)</li>
<li>Sort <b>sort </b> () used to provide sort definition for the results</li>
</ul>
</div>
<p> ;</p>
<h3 style="text-align: left;"><b>2. Methods for querying for documents-</b></h3>
<p>The query methods need to specify the target type T that will be returned and they are also overloaded with an explicit collection name for queries that should operate on a collection other than the one indicated by the return type.</p>
<div class="itemizedlist">
<ul >
<li><b>findAll </b> Query for a list of objects of type T from the collection.</li>
<li><b>findOne</b> Map the results of an ad-hoc query on the collection to a single instance of an object of the specified type.</li>
<li><b>findById</b> Return an object of the given id and target class.</li>
<li><b>find</b> Map the results of an ad-hoc query on the collection to a List of the specified type.</li>
<li><b>findAndRemove</b> Map the results of an ad-hoc query on the collection to a single instance of an object of the specified type. The first document that matches the query is returned and also removed from the collection in the database.</li>
</ul>
</div>
<p>In Spring data for <b>MongoDB</b>, you can use<b><i> findOne(), find() and getCollection() </i></b>to get / query documents from mongoDB. See some of the common ways :</p>
</div>
<pre class="highlight">Employee employee = new Employee(); 
 
 //get first found record, from "dojCollection" collection, where empId = 10001 
 Employee employee = mongoOperation.findOne(new Query(Criteria 
 .where("empId").is(10001)),"dojCollection", Employee.class); 
 
 //get all found records, from "dojCollection" collection, where empId <;= 10001 abs empAge = 21 
 List<;Employee>; employees = mongoOperation.find(new Query(Criteria 
 .where("empId").lte(10001).and("empAge").is(21)), "dojCollection", Employee.class); 
 
 //get all records from "dojCollection" collection 
 List<;Employee>; employees = mongoOperation.getCollection("dojCollection", Employee.class); 
</pre>
<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/springquery.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"/>; 
 <;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>; 
 
<;/beans>; 
</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 ... where empId = 1001 
 // find 
 Employee employee1 = mongoOperations.findOne(query(where("empId").is(1001)), Employee.class,"dojCollection"); 
 System.out.println(employee1); 
 System.out.println("***********************CASE 2************************"); 
 // Case 2 ... where empAge >;= 23 and salary = 70000 
 // find 
 List<;Employee>; employee2 = mongoOperations.find(query(where("salary").is(70000).and("empAge").gte(23)), Employee.class,"dojCollection"); 
 System.out.println(employee2); 
 System.out.println("***********************CASE 3************************"); 
 // Case 3 ... where empId <;= 10002 and age = 23 
 // find 
 List<;Employee>; employee = mongoOperations.find(query(where("empId").lte(10002).and("empAge").is(23)), Employee.class,"dojCollection"); 
 System.out.println(employee); 
 } 
} 
</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 />
Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]<br />
***********************CASE 2************************<br />
[Employee [age=26, empName=Dinesh Rajput, empId=1001, salary=70000]]<br />
***********************CASE 3************************<br />
[Employee [age=23, empName=Adesh Rajput, empId=1002, salary=30000], Employee [age=23, empName=Vinesh Rajput, empId=1003, salary=32000]]<br />
DONE!</div>
<h3><b>Download SourceCode+Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBSpringQueryDemo.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>MongoDBSpringQueryDemo.zip</b></a><br />
<b></b></h3>
<p><b>References</b><br />
You must read this <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>Spring’s mongodb query documentation</b></a>, to study more overloaded methods and criteria examples.</p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/spring-data-mongodb-update-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>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-update-document/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-delete-document/">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: '581'});
});
</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…