MongoTemplate Spring Boot Example MongoDB java Spring Boot by devs5003 - March 7, 2023February 21, 20241 Last Updated on February 21st, 2024In continuation to series of tutorials on Spring Boot with MongoDB, we have already discussed various examples using MongoRepository interface. Now in this article we are going to discuss a different way of accessing data from MongoDB. This is nothing but MongoTemplate. MongoTemplate is defined by Spring Data MongoDB, used to perform DB operations without using any repository interface. If you are reading this article in context of Spring Boot, you must have heard about the term JDBCTemplate. Like JDBCTemplate, MongoTemplate is a class which provides us different handy methods to work on various DB operations. However, we generally use it to retrieve data from MongoDB using different Criteria queries. Hence, our topic here is to discuss is ‘MongoTemplate Spring Boot Examples’. Of course, MongoRepository are more convenient than MongoTemplate but MongoTemplate offers you closer control over what you request from MongoDB. We can even utilize both of them in our programming practice as per our need and for performance enhancements. Moreover, MongoTemplate can offer an easier step to write a complex query than MongoRepository. Even some people in the industry also find that MongoTemplate is a better choice to write a complex query easily. Let’s start discussing our topic ‘MongoTemplate Spring Boot Examples’. Table of Contents Toggle What is MongoTemplate?MongoTemplate Spring Boot ExamplesCoding Steps to develop MongoTemplate Spring Boot ExamplesStep#0 : Setup MongoDB with Spring BootStep#1 : Create a Spring Boot Project using STS(Spring Tool Suite)Step#2 : Update application.propertiesStep#3 : Create Entity classsave(object) OR save(object, collectionName)insert( ) AND insertAll( )Using insert(Collection<? extends T> batchToSave, String collectionName)Using insertAll(Collection<? extends T> ObjectsToSave)findAll(className) OR findAll(className, collectionName)OutputfindById(id, entityClass) OR findById(id, entityClass, collectionName)findAndModify(query, update, entityClassName)updateMulti(query, update, entityClassName)findAndRemove(query, entityClassName)findAllAndRemove(query, entityClassName)upsert(query, update, entityClassName)Important Methods in MongoTemplateFAQWhen to use MongoTemplate rather than MongoRepository?ConclusionLinks to Other tutorials on MongoDB with Spring Boot What is MongoTemplate? MongoTemplate is nothing but a Java class that comes under org.springframework.data.mongodb.core package. It provides a set of rich features for interacting with MongoDB and acts as a central class for Spring’s MongoDB support. Moreover, MongoTemplate is thread-safe and can be reused across multiple instances. The MongoTemplate class implements the interface MongoOperations. Furthermore, MongoOperations has powerful APIs for Query, Criteria, and Update operations. Also, it offers methods using Generics. We can directly use MongoTemplate by auto-wiring it as a property in a class. MongoTemplate Spring Boot Examples Let’s develop some examples on Spring Boot using MongoTemplate. We will start with common coding steps that are prerequisite in order to develop various examples and then get into examples in the subsequent sections. Coding Steps to develop MongoTemplate Spring Boot Examples In order to develop and test Query examples, we will first write codes and insert some records into DB. Thereafter, we will start testing Query Examples step by step. Step#0 : Setup MongoDB with Spring Boot Make sure you already have installed MongoDB in your system. If not, kindly visit ‘How to install MongoDB in your system ?‘. Here, you will also get some handy commands to work with MongoDB. In order to get hold on Spring Boot with MongoDB, kindly visit ‘How to work with MongoDB in Spring Boot?‘. Step#1 : Create a Spring Boot Project using STS(Spring Tool Suite) Here, we will use STS(Spring Tool Suite) to create our Spring Boot Project. If you are new to Spring Boot, visit Internal Link to create a sample project in spring boot using STS. While creating a project in STS, add starters ‘Spring Data MongoDB’, and ‘Lombok’ in order to get features of MongoDB. Furthermore, if you are new to ‘Lombok’, kindly visit ‘How to configure Lombok‘ and to know all about it in detail. Step#2 : Update application.properties Update application.properties as below. spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=springBootMongoDB If you are using MongoDB in authentication mode, include username and password of it accordingly. Step#3 : Create Entity class Here we will use Book as an entity to illustrate the examples. Hence, create a Book.java class as below. However, we will consider collection name as ‘Books’ in MongoDB. It is just to illustrate the use of element ‘collection’ in @Document annotation. Moreover, we are using ‘Lombok‘ in order to reduce the boilerplate code. import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Document public class Book { @Id private Integer id; private String name; private Integer pages; private String author; private Double cost; } In this example, we have taken id as integer. If you are looking for an example where id as a String, kindly visit our previous tutorial on Spring Boot Mongo DB CRUD Example. save(object) OR save(object, collectionName) Both methods save records into DB. If we intentionally want to change the collection name, we can use save(object, collectionName). However, if we use save(object) method, it will automatically insert records into default collection. Here default name of collection is ‘book’. By default, Entity class name with first letter in lower case becomes the name of collection. Since our Entity class name is ‘Book’, as a result by default collection name will become ‘book’. import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; import com.dev.springboot.model.Book; @Component public class BookOperations implements CommandLineRunner { @Autowired private MongoTemplate mt; @Override public void run(String... args) throws Exception { mt.save(new Book(500, "Core Java", 200, "Kathy Sierra", 1065.5)); mt.save(new Book(501, "JSP & Servlets", 350, "Kathy Sierra", 1749.0)); // mt.save(new Book(501, "JSP & Servlets", 350, "Kathy Sierra", 1749.0),"Book"); // save () with collection name 'Book' mt.save(new Book(502, "Spring in Action", 480, "Craig Walls", 940.75)); mt.save(new Book(503, "Pro Angular", 260, "Freeman", 1949.25)); mt.save(new Book(504, "HTML CSS", 100, "Thomas Powell", 2317.09)); mt.save(new Book(505, "Hibernate in Action", 180, "Gavin King", 889.25)); mt.save(new Book(506, "Practical MongoDB", 180, "Shakuntala Gupta", 785.0)); mt.save(new Book(507, "Pro Spring Boot", 850, "Felipe Gutierrez", 2167.99)); mt.save(new Book(508, "Beginning jQuery", 180, "Franklin", 1500.00)); mt.save(new Book(509, "Java Design Patterns", 114, "Devendra Singh", 919.99)); System.out.println("------All records has been saved successfully-------"); } } In the above example, we have illustrated one record with collection name of our choice ‘Book’ and commented it. If you uncomment it, a new record in a new collection ‘Book’ will be created. insert( ) AND insertAll( ) However, these methods are also used to save records into DB. Generally, we use these methods if we want to insert multiple records( batch records) into DB. insert() comes with a parameter as collection name while insertAll() doesn’t come with the same. Below screenshot shows the various flavors of these methods. For example, let’s use these methods to create same number of records as we did in previous example of save() operation. Please note that we are using List.of() method to save multiple records in DB. However, It will work on JDK9 and above versions. You can also use Arrays.asList() method to save records if you are using lower than JDK9 version. Using insert(Collection<? extends T> batchToSave, String collectionName) mt.insert(List.of( new Book(500, "Core Java", 200, "Kathy Sierra", 1065.5), new Book(501, "JSP & Servlets", 350, "Kathy Sierra", 1749.0), new Book(502, "Spring in Action", 480, "Craig Walls", 940.75), new Book(503, "Pro Angular", 260, "Freeman", 1949.25), new Book(504, "HTML CSS", 100, "Thomas Powell", 2317.09), new Book(505, "Hibernate in Action", 180, "Gavin King", 889.25), new Book(506, "Practical MongoDB", 180, "Shakuntala Gupta", 785.0), new Book(507, "Pro Spring Boot", 850, "Felipe Gutierrez", 2167.99), new Book(508, "Beginning jQuery", 180, "Franklin", 1500.00), new Book(509, "Java Design Patterns", 114, "Devendra Singh", 919.99) ), "Book" ); Using insertAll(Collection<? extends T> ObjectsToSave) mt.insertAll(List.of( new Book(500, "Core Java", 200, "Kathy Sierra", 1065.5), new Book(501, "JSP & Servlets", 350, "Kathy Sierra", 1749.0), new Book(502, "Spring in Action", 480, "Craig Walls", 940.75), new Book(503, "Pro Angular", 260, "Freeman", 1949.25), new Book(504, "HTML CSS", 100, "Thomas Powell", 2317.09), new Book(505, "Hibernate in Action", 180, "Gavin King", 889.25), new Book(506, "Practical MongoDB", 180, "Shakuntala Gupta", 785.0), new Book(507, "Pro Spring Boot", 850, "Felipe Gutierrez", 2167.99), new Book(508, "Beginning jQuery", 180, "Franklin", 1500.00), new Book(509, "Java Design Patterns", 114, "Devendra Singh", 919.99) )); Ultimately, same records will get inserted into DB using any of methods. findAll(className) OR findAll(className, collectionName) Above both methods gets data from DB collection as List<T> format. Here T is Class name. If class name and collection name both are same then use findAll(T.class), else use findAll(T.class, “collectionName”). Let’s retrieve the records saved in the previous save() example. For example, below code will retrieve the records from DB. List<Book> list = mt.findAll(Book.class); //List<Book> list = mt.findAll(Book.class,"Book"); //If collection name & the Entity Class Name are different (case-sensitive) list.forEach(System.out::println); Output If we use the code ‘List<Book> list = mt.findAll(Book.class)’, we will get the below result. Book(id=500, name=Core Java, pages=200, author=Kathy Sierra, cost=1065.5) Book(id=501, name=JSP & Servlets, pages=350, author=Kathy Sierra, cost=1749.0) Book(id=502, name=Spring in Action, pages=480, author=Craig Walls, cost=940.75) Book(id=503, name=Pro Angular, pages=260, author=Freeman, cost=1949.25) Book(id=504, name=HTML CSS, pages=100, author=Thomas Powell, cost=2317.09) Book(id=505, name=Hibernate in Action, pages=180, author=Gavin King, cost=889.25) Book(id=506, name=Practical MongoDB, pages=180, author=Shakuntala Gupta, cost=785.0) Book(id=507, name=Pro Spring Boot, pages=850, author=Felipe Gutierrez, cost=2167.99) Book(id=508, name=Beginning jQuery, pages=180, author=Franklin, cost=1500.0) Book(id=509, name=Java Design Patterns, pages=114, author=Devendra Singh, cost=919.99) findById(id, entityClass) OR findById(id, entityClass, collectionName) We use this method to fetch data from DB collection using PK(ID). If Id exist then JSON Document is converted into Object, else it returns null (which indicates no object). For example, below code will retrieve the required result. Book book = mt.findById(504, Book.class); //Book book = mt.findById(501, Book.class,"Book"); System.out.println(book); If we run the above statements, We will get the required output. findAndModify(query, update, entityClassName) We use this method to fetch data based on given condition (query) and then modify data for given update type. We will require two objects to complete the whole process. 1)’Query’ object to fetch data from Collection that needs to be modified 2)’Update’ to specify which key=value combination need to be modified for the provided Result by Query. Query query= new Query(); query.addCriteria(Criteria.where("id").is(501)); Update update = new Update(); update.set("cost", 1065.25); update.set("name", "Core Java"); mt.findAndModify(query, update, Book.class); System.out.println("Data Modified"); If you check the result from DB also, you will find the updated values of the record. updateMulti(query, update, entityClassName) This method updates all the records of the DB that matches the given criteria. For the example, in below code we are trying to update the cost of all Books by 999.0 which have pages count less than or equals to 180. Query query= new Query(); query.addCriteria(Criteria.where("pages").lte(180)); Update update = new Update(); update.set("cost", 999.0); mt.updateMulti(query, update, Book.class); findAndRemove(query, entityClassName) We use this method to remove data which are actually fetched from a given condition. Query query= new Query(); query.addCriteria(Criteria.where("cost").is(1749.0)); mt.findAndRemove(query, Book.class); Here in the above example, we are deleting a Book whose cost is equal to 1749.0. findAllAndRemove(query, entityClassName) We utilize this method to remove multiple records which are actually fetched from a given condition. Query query= new Query(); query.addCriteria(Criteria.where("cost").gte(1000.0)); mt.findAllAndRemove(query, Book.class); Here in the above example, we are deleting all the Books whose cost is greater than or equal to 1000.0. upsert(query, update, entityClassName) This method should be new to many of us. The word ‘upsert’ is the combination of words ‘update’ and ‘insert’. When the given criteria matches any record in DB, upsert() will update that record. If it doesn’t find any record of the given criteria, then it will insert a new record. Query query= new Query(); query.addCriteria(Criteria.where("id").is(510)); Update update = new Update(); update.set("cost", 1065.25); update.set("name", "Core Java"); mt.upsert(query, update, Book.class); Here in the above example, we are trying to update a record which doesn’t exist in the DB. Hence upsert() will create a new record with updated value leaving other fields as null. Below is the record which will get inserted after executing the above code. Book(id=510, name=Core Java, pages=null, author=null, cost=1065.25) Important Methods in MongoTemplate FAQ When to use MongoTemplate rather than MongoRepository? MongoTemplate is an appropriate choice if you want to use large and complex queries and interact with MongoDB in a flexible manner. MongoRepository is a high-level abstraction on top of MongoTemplate. This interface is a suitable choice if you want to interact with MongoDB using a higher level of abstraction, with sensible defaults and some built-in features. In summary, MongoTemplate offers more control and flexibility, whereas MongoRepository provides more convenience and abstraction. Depending on your use case, you should choose the one that better suits your requirements. Conclusion We have covered a bit of theoretical knowledge and enough amount of examples on ‘MongoTemplate Spring Boot Examples’. Now we should be able to work on MongoTemplate with a Spring Boot project confidently. However, we have covered all the important methods which are used by the people in the industry in most of the cases. Should you need any further assistance in this area, you may visit one of the official documentation. Additionally, If you want to learn more on NoSQL databases and have a good understanding of them, kindly visit a separate article on ‘All About NoSQL Databases‘. Links to Other tutorials on MongoDB with Spring Boot Below are the links to learn MongoDB with Spring Boot extensively. MongoDB Basics & How to work with Spring Boot Spring Boot MongoDB CRUD Examples Spring Boot MongoDB @Query Examples Related