Spring Data MongoTemplate Example

By Arvind Rai, September 24, 2019
This page will walk through Spring Data MongoTemplate example. The MongoTemplate class is the primary implementation of MongoOperations interface which specifies the basic set of MongoDB operations. We can also use MongoRepository interface to perform MongoDB operations. The implementation class of MongoRepository uses MongoTemplate bean at run time. To create MongoTemplate bean we need to create MongoClient using MongoDB server host, port and database name with given credentials. MongoTemplate has methods such as insert, update, remove, find, upsert etc.
Here on this page we will provide how to configure MongoClient and MongoTemplate using JavaConfig as well as XML configuration. We will also provide examples to use methods of MongoTemplate and MongoRepository step-by-setp.

1. Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.1.9.RELEASE
3. Spring Data 2.1.10.RELEASE
4. Spring Boot 2.1.7.RELEASE
5. MongoDB Server 4.0
6. Maven 3.5.2

2. Setup MongoDB Server

Find the steps to setup MongoDB server.
1. Install MongoDB from the link.
2. Go to installation directory /MongoDB/Server/4.0/bin
3. Click on mongod.exe, server will be started.
4. Now click on mongo.exe and a command prompt will open.
5. Write command use <db_name> such as
> use myMongoDB 
Database will be created and you will be switched in that database named as myMongoDB.
6. Now create a user with username mdbUser and password cp, run the below code in command prompt.
db.createUser(
  {
    user: "mdbUser",
    pwd: "cp",
    roles: [
       { role: "readWrite", db: "myMongoDB" }
    ]
  }
) 

3. Maven Dependencies

Find the Maven dependencies of our project.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.7.RELEASE</version>
	<relativePath />
</parent>
<properties>
	<context.path>spring-app</context.path>
	<java.version>11</java.version>
</properties>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-mongodb</artifactId>
	</dependency>
</dependencies> 

4. MongoDB Java Configuration

Find the Java configuration to integrate MongoDB with Spring Data.
MongoDBConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@EnableMongoRepositories(basePackages = "com.concretepage.repository")
public class MongoDBConfig {
	public String getDatabaseName() {
		return "myMongoDB";
	}
	@Bean
	public MongoClient mongoClient() {
		ServerAddress address = new ServerAddress("127.0.0.1", 27017);
		MongoCredential credential = MongoCredential.createCredential("mdbUser", getDatabaseName(), "cp".toCharArray());
		MongoClientOptions options = new MongoClientOptions.Builder().build();
        
		MongoClient client = new MongoClient(address, credential, options);
		return client;
	}
	@Bean
	public MongoDbFactory mongoDbFactory() {
		MongoDbFactory factory = new SimpleMongoDbFactory(mongoClient(), getDatabaseName());
		return factory;
	}
	@Bean
	public MongoTemplate mongoTemplate() {
		MongoTemplate template = new MongoTemplate(mongoDbFactory());
		return template;
	}
} 
MongoClient: It is a MongoDB client with internal connection pooling. The MongoClient class is from com.mongodb.MongoClient MongoDB package.
MongoDbFactory: Provides Mongo database instance.
MongoTemplate: It is the primary implementation of MongoOperations.
@EnableMongoRepositories: Activates MongoDB repositories.

We can also use AbstractMongoConfiguration to configure MongoDB. AbstractMongoConfiguration is a base class for Spring Data MongoDB configuration using JavaConfig with MongoClient and MongoTemplate. We need not to create separate bean for MongoTemplate in this case.
MongoDBConfig.java
package com.concretepage.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
@EnableMongoRepositories(basePackages = "com.concretepage.repository")
public class MongoDBConfig extends AbstractMongoConfiguration {
	@Override
	public String getDatabaseName() {
		return "myMongoDB";
	}
	@Override
	@Bean
	public MongoClient mongoClient() {
		ServerAddress address = new ServerAddress("127.0.0.1", 27017);
		MongoCredential credential = MongoCredential.createCredential("mdbUser", getDatabaseName(), "cp".toCharArray());
		MongoClientOptions options = new MongoClientOptions.Builder().build();
        
		MongoClient client = new MongoClient(address, credential, options);
		return client;
	}
} 
MongoCredential.createCredential method has following syntax.
createCredential(String userName, String database, char[] password) 

5. MongoDB XML Configuration

Find the XML configuration to integrate MongoDB with Spring Data.
mongodb-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/data/mongo 
          https://www.springframework.org/schema/data/mongo/spring-mongo.xsd
          http://www.springframework.org/schema/beans
          https://www.springframework.org/schema/beans/spring-beans.xsd">

        <mongo:repositories base-package="com.concretepage.repository"/>
    
	<mongo:mongo-client host="localhost" port="27017" credentials="mdbUser:cp@myMongoDB" id="mongoClient" />
	
	<mongo:db-factory dbname="myMongoDB" mongo-ref="mongoClient" id="mongoDbFactory"/>
	
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
	  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
	</bean>	

</beans> 
<mongo:repositories>: Specify the base package containing the MongoRepository implementation classes.
<mongo:mongo-client>: Creates MongoClient using host, port and credentials. The format of credential is username:password@database.
<mongo:db-factory>: Creates MongoDbFactory and using this we create MongoTemplate bean.

6. Using MongoTemplate

The MongoTemplate class is the primary implementation of MongoOperations interface which specifies the basic set of MongoDB operations. Find the sample example to use MongoTemplate.
MongoTemplateTest.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.concretepage.config.MongoDBConfig;
import com.concretepage.entity.Student;
public class MongoTemplateTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MongoDBConfig.class);
		ctx.refresh();
		MongoTemplate mongoTemplate = ctx.getBean(MongoTemplate.class);

		mongoTemplate.dropCollection(Student.class);

		Student ram = new Student(101, "Ram", 19);
		Student shyam = new Student(102, "Shyam", 19);
		Student mohan = new Student(103, "Mohan", 20);
		mongoTemplate.insert(Arrays.asList(ram, shyam, mohan), Student.class);

		Query query = new Query();
		query.addCriteria(Criteria.where("age").is(19));
		List<Student> list = mongoTemplate.find(query, Student.class, "student");
		list.forEach(std -> System.out.println(std.getName() + " - " + std.getAge()));
		
		ctx.registerShutdownHook();
		ctx.close();		
	}
} 
Find the entity class used in our example.
Student.java
package com.concretepage.entity;
import org.springframework.data.annotation.Id;
public class Student { 
	@Id
	private Integer id;
	private String name;
	private Integer age;
	public Student(Integer id, String name, Integer age){
		this.id = id;
		this.name=name;
		this.age=age;
	}
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public Integer getAge() {
		return age;
	}
} 
Output
Ram - 19
Shyam - 19 
We can see our inserted data in student collection in MongoDB database as following.
Spring Data MongoTemplate Example
MongoTemplate performs many operations such as insert, update, remove, find, upsert etc. Let us discuss some of the methods of MongoTemplate class.

6.1 insert

To insert a document into MongoDB collection, the MongoTemplate provides insert method. Find the code to insert one document.
Student ram = new Student(1,"Ram",20);
mongoTemplate.insert(ram); 
To check the data in table, run the command in Mongo command prompt.
> db.student.find() 
We will find the document as following.
{ "_id" : 1, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" } 
Find the code to insert collection of documents.
Student ram = new Student(1,"Ram",20);
Student shyam = new Student(2,"Shyam",19);
Student mohan = new Student(3,"Mohan",20);	

mongoTemplate.insert(Arrays.asList(ram, shyam, mohan), Student.class); 
Data will be inserted as following.
{ "_id" : 1, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 2, "name" : "Shyam", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 3, "name" : "Mohan", "age" : 20, "_class" : "com.concretepage.entity.Student" } 

6.2 save

The save method saves the document to collection for the entity type of the given object. When we pass collection name, then document is saved in the specified collection, even if entity is of different type.
Student ram = new Student(101,"Ram",20);
mongoTemplate.save(ram);

Person newPerson = new Person(102, "Shyam");
mongoTemplate.save(newPerson, "student"); 
The data in student collection will be saved as following.
{ "_id" : 101, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Shyam", "_class" : "com.concretepage.entity.Person" } 


6.3 collectionExists

As we have a collection named as student in our database, so for collectionExists(Student.class), we will get true value. If we drop the student collection from database then collectionExists(Student.class) will return false.
boolean stdExists = mongoTemplate.collectionExists(Student.class);
System.out.println(stdExists); //true 

6.4 updateFirst

updateFirst method updates the first document found by the given criteria.
For the example, find the initial state of student collection in our database.
{ "_id" : 101, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Shyam", "age" : 19, "_class" : "com.concretepage.entity.Student" } 
Create the instance of Spring MongoDB Query and Update and then call updateFirst by MongoTemplate instance.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
Update update = new Update();
update.set("name", "Mohan");
update.set("age", 25);
mongoTemplate.updateFirst(query, update, Student.class); 
Our collection data will be updated.
{ "_id" : 101, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Mohan", "age" : 25, "_class" : "com.concretepage.entity.Student" } 

6.5 updateMulti

updateMulti method updates all the data of the collection that matches the given criteria. For the example, we have following initial data of student collection.
{ "_id" : 101, "name" : "Ram", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Shyam", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 103, "name" : "Mohan", "age" : 20, "_class" : "com.concretepage.entity.Student" } 
Use updateMulti method as following.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
Update update = new Update();
update.set("name", "Shiva");
update.set("age", 30);
mongoTemplate.updateMulti(query, update, Student.class); 
Our all data will be updated that matches the criteria.
{ "_id" : 101, "name" : "Shiva", "age" : 30, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Shiva", "age" : 30, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 103, "name" : "Mohan", "age" : 20, "_class" : "com.concretepage.entity.Student" } 

6.6 upsert

upsert method accepts Query, Update and entity class as arguments. upsert performs an upsert that means when the given criteria matches any data in collection, upsert will update that row. If upsert does not find any data by given criteria, then a new row will be inserted.
For the example, find the initial data in our collection.
{ "_id" : 101, "name" : "Ram", "age" : 19, "_class" : "com.concretepage.entity.Student" } 
Find the code to upsert a collection.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
Update update = new Update();
update.set("name", "Shiva");
update.set("age", 30);
mongoTemplate.upsert(query, update, Student.class); 
As Query finds a row by given criteria, so that row is updated.
{ "_id" : 101, "name" : "Shiva", "age" : 30, "_class" : "com.concretepage.entity.Student" } 

6.7 exists

exists method checks the existence of at least one element in the collection according to the given criteria.
Suppose following initial data.
{ "_id" : 101, "name" : "Ram", "age" : 20, "_class" : "com.concretepage.entity.Student" }
Look for the existence of a student named as Ram.
Query query = new Query(); 
query.addCriteria(Criteria.where("name").is("Ram"));

boolean dataExists = mongoTemplate.exists(query, "student");
System.out.println(dataExists); //true 

6.8 find

find method fetches the documents for the given Query and returns a list.
For the demo, we have initial documents in our collection.
{ "_id" : 101, "name" : "Mahesh", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Krishna", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 103, "name" : "Shiva", "age" : 22, "_class" : "com.concretepage.entity.Student" } 
Find the code snippet to use find method.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
List<Student> list = mongoTemplate.find(query, Student.class, "student");
list.forEach(std -> System.out.println(std.getName() + " - " + std.getAge() )); 
Output
Mahesh - 19
Krishna - 19 

6.9 findAll

findAll method finds all documents of the collection. We can also specify entity type to fetch all data from collection of specified entity type only.
List<Student> list = mongoTemplate.findAll(Student.class, "student");
list.forEach(std -> System.out.println(std.getName() + " - " + std.getAge() )); 
Output
Mahesh - 19
Krishna - 19
Shiva - 22 

6.10 findAllAndRemove

findAllAndRemove method removes all the documents matching the given query document criteria. For the example, we have following initial documents.
{ "_id" : 101, "name" : "Mahesh", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 102, "name" : "Krishna", "age" : 19, "_class" : "com.concretepage.entity.Student" }
{ "_id" : 103, "name" : "Shiva", "age" : 22, "_class" : "com.concretepage.entity.Student" } 
Find the code to use findAllAndRemove method.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
List<Student> list = mongoTemplate.findAllAndRemove(query, Student.class, "student");
list.forEach(std -> System.out.println(std.getName() + " - " + std.getAge() )); 
findAllAndRemove method will return list of documents matching the criteria.
Mahesh - 19
Krishna - 19 
All matching documents will be deleted from collection in the database and following document will be left.
{ "_id" : 103, "name" : "Shiva", "age" : 22, "_class" : "com.concretepage.entity.Student" } 

6.11 remove

remove method removes the documents from the collection for the matching criteria.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
mongoTemplate.remove(query, Student.class, "student"); 

6.12 count

count method returns the number of documents matching the criteria.
Query query = new Query(); 
query.addCriteria(Criteria.where("age").is(19));
long count = mongoTemplate.count(query, "student");
System.out.println(count); 

6.13 dropCollection

dropCollection method drops the collection with the name indicated by the entity class.
mongoTemplate.dropCollection(Student.class); 

7. Using MongoRepository

Mongo database operation can be performed using MongoRepository interface. We need to create a class implementing MongoRepository. At runtime Spring Data provides implementation of MongoRepository interface methods to interact with MongoDB. At runtime it uses MongoTemplate by itself. The MongoRepository has methods such as findAll, insert and saveAll. We can also create our own specific methods. Find the example.
StudentRepository.java
package com.concretepage.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;
import com.concretepage.entity.Student;

@Component
public interface StudentRepository extends MongoRepository<Student, Integer> {
    Student getStudentById(int id);
    List<Student> getStudentByAge(int age);
} 
Find the Main class to test Mongo repository.
MongoRepositoryTest.java
package com.concretepage;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.config.MongoDBConfig;
import com.concretepage.entity.Student;
import com.concretepage.repository.StudentRepository;
public class MongoRepositoryTest {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(MongoDBConfig.class);
		ctx.refresh();
		StudentRepository repository = ctx.getBean(StudentRepository.class);

		repository.deleteAll();

		Student lakshmi = new Student(101, "Lakshmi", 22);
		Student parvati = new Student(102, "Parvati", 22);
		Student saraswati = new Student(103, "Saraswati", 24);

		repository.insert(lakshmi);
		repository.insert(parvati);
		repository.insert(saraswati);

		List<Student> list = repository.getStudentByAge(22);
		list.forEach(std -> System.out.println(std.getName() + " - " + std.getAge()));

		ctx.registerShutdownHook();
		ctx.close();
	}
} 
Output
Lakshmi - 22
Parvati - 22 

8. References

Class MongoClient
Spring Data MongoDB Reference
MongoDB Tutorials

9. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us