Home » Framework » All the find queries of MongoTemplate in Spring MongoDB

All the find queries of MongoTemplate in Spring MongoDB

This article explains how to use all the find queries of MongoTemplate in the Spring Boot Application which is using spring-boot-starter-data-mongodb as a dependency. All the examples described here are tested under version 2.5.2 of Spring Boot.

We have already seen the CRUD operations of MongoTemplate. If you want to know that please take a look at Spring MongoDB CRUD Operations.

Let's take the below table of information to perform all the find queries of MongoTemplate.

_idfirstNamelastNameagepincoderoles
1JohnPaul20123456["USER","ADMIN",MANAGER"]
2NivinPaul20123456["USER","ADMIN"]
3RajaSekar35123457["USER"]
4David Ram45123457["USER"]

Here the collection name of the above table is "user_profile" in MongoDB and the entity structure of the above table in Spring Boot looks like below.

package com.tipstocode.model;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection  = "user_profile")
public class ProfileVO {	
	@Id
	private ObjectId _id;	
	private String firstName;	
	private String lastName;	
	private int age;	
	private String pincode;	
	private List<String> roles = new ArrayList<String>();	
	
	public String get_id() {
		return _id.toHexString();
	}
	public void set_id(ObjectId _id) {
		this._id = _id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public List<String> getRoles() {
		return roles;
	}
	public void setRoles(List<String> roles) {
		this.roles = roles;
	}
	public String getPincode() {
		return pincode;
	}
	public void setPincode(String pincode) {
		this.pincode = pincode;
	}
}

Now Let's start to test all the find queries of MongoTemplate with the above table of information.

Find, FindById, FindOne, and FindDistinct queries of MongoTemplate

Find Query

Find query fetches the list of records in a collection (or) table based on the query we write in it. There are two types of query formats available in find query.

  1. find(Query query, Class<T> entityClass)
  2. find(Query query, Class<T> entityClass, String collectionName)

Now let's see the example of first one find(Query query, Class entityClass).

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));	
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records that matches the "lastName" with "Paul". See the output below.

1JohnPaul20123456["USER","ADMIN",MANAGER"]
2NivinPaul20123456["USER","ADMIN"]

We can test the same query with the other format find(Query query, Class<T> entityClass, String collectionName). It returns the same output as above. The example is below.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));	
return mongoTemplate.find(query, ProfileVO.class,"user_profile");

FindById Query

FindById fetches the single record based on the _id (ObjectId). Here also there are two formats available.

  1. findById(Object id, Class<T> entityClass)
  2. findById(Object id, Class<T> entityClass, String collectionName)

The below are examples of both formats.

return mongoTemplate.findById("1", ProfileVO.class);
return mongoTemplate.findById("1", ProfileVO.class, "user_profile");

The output for both formats is the same and is given below.

1JohnPaul20123456["USER","ADMIN",MANAGER"]

FindOne Query

FindOne Query fetches the single record based on the query we write in it. Here also there are two formats available.

  1. findOne(Query query, Class<T> entityClass)
  2. findOne(Query arg0, Class<T> arg1, String arg2)

Here the second format looks different right. We may have doubt that what the arguments arg0, arg1, and arg2 describe?. No confusion it's simple, arg0 describes query, arg1 describes Entity Class and arg2 describes collection name. That's it. Let see the examples below then you can easily understand them.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));	
return mongoTemplate.findOne(query, ProfileVO.class);
Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));	
return mongoTemplate.findOne(query, ProfileVO.class, "user_profile");

The output for both the queries is the same and is given below.

1JohnPaul20123456["USER","ADMIN",MANAGER"]

Note: In the example table there are two records available that match the 'lastName' with 'Paul'. But the query returns only one. Yes, obviously it returns the first matching record based on the insertion order.

FindDistinct Query

FindDistinct query fetches the list of unique records based on the field we mentioned in the query and returns that. Here there are four formats are available.

  1. findDistinct(String field, Class<?> entityClass, Class<T> resultClass)
  2. findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass)
  3. findDistinct(Query query, String field, String collection, Class<T> resultClass)
  4. findDistinct(Query arg0, String arg1, String arg2, Class<?> arg3, Class<T> arg4)

The example of first format is below

List<String> pincodes = mongoTemplate.findDistinct("pincode", ProfileVO.class, String.class);		
return pincodes;

The above query returns the list of string values that contains the unique values of the field 'pincode'. The output is below.

[
    "123456",
    "123457"
]

In all other formats of findDistinct returns the list of records that contains the unique values based on the field and the query, we write in it. Now let's see the example of the second format.

Query query = new Query();
query.addCriteria(Criteria.where("age").gt(20));
List<String> pincodes = mongoTemplate.findDistinct(query , "pincode", ProfileVO.class, String.class);		
return pincodes;

The above query returns the list of string values that contain the unique pin codes when the age is greater than 20. The output is below.

[
    "123457"
]

Now let us see all other formats of FindDistinct query which is using the same Criteria query and which returns the same output.

Query query = new Query();
query.addCriteria(Criteria.where("age").gt(20));
List<String> pincodes = mongoTemplate.findDistinct(query , "pincode", "user_profile", String.class);		
return pincodes;
Query query = new Query();
query.addCriteria(Criteria.where("age").gt(20));
List<String> pincodes = mongoTemplate.findDistinct(query , "pincode", "user_profile", ProfileVO.class, String.class);		
return pincodes;

FindAll, FindAllAndRemove, FindAndModify, FindAndRemove and FindAndReplace queries of MongoTemplate

Now let start to see how to use findAll, findAllAndRemove, and all other find queries of MongoTemplate which is existing in Spring Data MongoDB.

FindAll Query

FindAll Query fetches all the records in a collection. There are two formats available in FindAll Query.

  1. findAll(Class<T> entityClass)
  2. findAll(Class<T> entityClass, String collectionName)

The below are examples of both formats.

return mongoTemplate.findAll(ProfileVO.class);
return mongoTemplate.findAll(ProfileVO.class, "user_profile");

The above two queries produce all the records in a collection of "user_profile". The output of the query is below.

1JohnPaul20123456["USER","ADMIN",MANAGER"]
2NivinPaul20123456["USER","ADMIN"]
3RajaSekar35123457["USER"]
4David Ram45123457["USER"]

FindAllAndRemove Query

FindAllAndRemove query removes the list of records based on the query we write in it. There are three formats available for this query.

  1. findAllAndRemove(Query query, Class<T> entityClass)
  2. findAllAndRemove(Query query, String collectionName)
  3. findAllAndRemove(Query query, Class<T> entityClass, String collectionName)

Let me give all the examples one by one below. All the examples use the same criteria and produce the same result but the format of the query is different.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
mongoTemplate.findAllAndRemove(query, ProfileVO.class);
Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
mongoTemplate.findAllAndRemove(query, "user_profile");
Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
mongoTemplate.findAllAndRemove(query, ProfileVO.class, "user_profile");

The above three formats of query remove all the records when the last name is 'Paul'. You can check that by fetching all the records using the findAll query. The output looks like below.

3RajaSekar35123457["USER"]
4David Ram45123457["USER"]

FindAndRemove Query

FindAndRemove query removes the single record based on the query. If the query matches with multiple records then it removes the first matching record based on the insertion order, I mean the record which is inserted first in the collection. There are two formats available in this query.

  1. findAndRemove(Query query, Class<T> entityClass)
  2. findAndRemove(Query query, Class<T> entityClass, String colletionName)

The examples of both formats are given below.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
mongoTemplate.findAndRemove(query, ProfileVO.class);
Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
mongoTemplate.findAndRemove(query, ProfileVO.class, "user_profile");

The above two queries remove the first matching single record whose last name is 'Paul'.

FindAndModify Query

FindAndModify query finds the single record based on the query and updates the same record based on the update definition we write in it. if the query matches multiple records then it updates the first matching record. Here also four formats available.

  1. findAndModify(Query query, UpdateDefinition update, Class<T> entityClass)
  2. findAndModify(Query query, UpdateDefinition update, Class<T> entityClass, String collectionName)
  3. findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass)
  4. findAndModify(Query query, UpdateDefinition update, FindAndModifyOptions options, Class<T> entityClass, String collectionName)

First, let us see the examples of the first two formats. For that, we have to write the criteria query to find the record and write the update definition to update the same record. The below query contains both.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
		
Update updateDef = new Update();
updateDef.set("firstName", "Peter");

return mongoTemplate.findAndModify(query, updateDef, ProfileVO.class);
Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
		
Update updateDef = new Update();
updateDef.set("firstName", "Peter");

return mongoTemplate.findAndModify(query, updateDef, ProfileVO.class, "user_profile");

The above two formats of the query do the same thing. It finds the record of which lastName is 'Paul' and updates the same record with firstName as 'Peter'.

The other two formats of FindAndModify query uses one extra option which is FindAndModifyOptions. Let see what the option is?. How to use the option?. and How it differs from the first two formats of query?.

There are several options available in the FindAndModifyOptions. Here let me explain the most used one that is returnNew() option.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
		
Update updateDef = new Update();
updateDef.set("firstName", "Peter");

return mongoTemplate.findAndModify(query, updateDef, new FindAndModifyOptions().returnNew(true), ProfileVO.class);

The above query fetches the matching record which lastName is 'Paul' and updates the same record with firstName as 'Peter'. You may have the question that the first two formats also do the same thing without this FindAndModifyOptions. Right!. But what is the difference between these?

Simple!. The first two formats without using FindAndModifyOptions return the old record I mean the record which is of before update and the last two formats which is using FindAndModifyOptions returns the updated object.

FindAndReplace Query

FindAndReplace query replaces the single record with the new one based on the query. Here also many formats are available.

  1. findAndReplace(Query query, T replacement)
  2. findAndReplace(Query query, T replacement, FindAndReplaceOptions options)
  3. findAndReplace(Query query, T replacement, String collectionName)
  4. findAndReplace(Query query, T replacement, FindAndReplaceOptions options, String collectionName)
  5. findAndReplace(Query query, T replacement, FindAndReplaceOptions options, Class<S> entityType, Class<T> resultType)
  6. findAndReplace(Query query, T replacement, FindAndReplaceOptions options, Class<T> resultType, String collectionName)
  7. findAndReplace(Query query, T replacement, FindAndReplaceOptions options, Class<S> entityType, String collectionName)

Here let me explain the first two formats and hope you can test other formats too. The below are examples of the first two formats of findAndReplace query.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
		
ProfileVO replacement = new ProfileVO();
replacement.setFirstName("Mullah");

return mongoTemplate.findAndReplace(query, replacement);

The above query fetches the first matching record which lastName is 'Paul' and replaces it with the new record which is having only the value of firstName that is 'Mullah' and other fields are empty. Now you can test it by using findAll Query. The output is below

1MullahPaul0null[]
2NivinPaul20123456["USER","ADMIN"]
3RajaSekar35123457["USER"]
4David Ram45123457["USER"]

The below query also gives the same result as FindAndReplaceOptions. The only difference is, it returns the replaced record, not the old one.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
		
ProfileVO replacement = new ProfileVO();
replacement.setFirstName("Mullah");
return mongoTemplate.findAndReplace(query, replacement, new FindAndReplaceOptions().returnNew());

Hope you understood all the find queries of MongoTemplate in Spring Data MongoDB. In the next article let me cover all the criteria queries of MongoTemplate. Thanks!. Keep Reading!.

Leave a Reply

Your email address will not be published. Required fields are marked *