Skip to content

MongoTemplate vs MongoRepository

  • by
MongoTemplate vs MongoRepository

1. Overview

In this article, we will learn the differences between MongoTemplate vs MongoRepository.

MongoDB and Spring Boot interact using the MongoTemplate class and MongoRepository interface.

2. MongoTemplate vs MongoRepository

The MongoTemplate class is the primary implementation of the MongoOperations interface that specifies the basic set of MongoDB operations. MongoRepository is from the Spring Data JPA library, a repository interface specific to Mongo DB.

MongoRepository extends the CrudRepository interface that contains methods to perform basic CRUD operations. For writing custom queries and aggregations, and for finer control over query filters, we can use the MongoTemplate class. MongoTemplate class implements interfaces that support operations like aggregation, find, update, upsert, index, remove, and more.

  • MongoTemplateMongoTemplate implements a set of ready-to-use APIs. A good choice for operations like update, aggregations, and others, MongoTemplate offers finer control over custom queries.
  • MongoRepositoryMongoRepository is used for basic queries that involve all or many fields of the document. Examples include data creation, viewing documents, and more.

Spring Boot MongoDB configuration using both approaches needs only a few lines of code.

MongoTemplate provides out-of-the-box functionalities present in the org.springframework.data.mongodb.core.query package. We don’t need to write many lines of code and we can do the update in a single database interaction. So we can use MongoTemplate for more complex operations.

For example, we will do the update in a single database transaction as compared to with MongoRepository, where we had to do three operations, i.e., find, set, and then save. MongoTemplate also provides the updateMulti() method, to update multiple documents in a single go.

MongoTemplate can do sorting, aggregations, finding the desired document based on multiple criteria and many more things, which is more efficient and increases the overall performance since the calculation/filtering is happening at the database level rather than fetching all the documents and writing huge complex code to filter out the desired documents.

3. Dependency

We can use both MongoTemplate and MongoRepository by adding the spring-boot-starter-data-mongodb dependency in pom.xml in case of Spring boot application.

Otherwise, add the below dependency for the spring application.

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
</dependency>

Let’s see the difference in terms of the update operation.

4. MongoRepository

We activate the Mongo Repositories using @EnableMongoRepositories.

@SpringBootApplication
@EnableMongoRepositories
public class MdbSpringBootApplication implements CommandLineRunner{
    
    @Autowired
    ItemRepository ItemRepo;
    
    public static void main(String[] args) {
        SpringApplication.run(MdbSpringBootApplication.class, args);
    }
}
public interface ItemRepository extends MongoRepository { 
public void updateCategoryName(String category) {
         

         String newCategory = "munchies";
         

         List<GroceryItem> list = groceryItemRepo.findAll(category);
         
         list.forEach(item -> {

             item.setCategory(newCategory);
         });
         

         List<GroceryItem> itemsUpdated = groceryItemRepo.saveAll(list);
         
         if(itemsUpdated != null)
             System.out.println("Successfully updated " + itemsUpdated.size() + " items.");         
     }
}

To update multiple documents, we have to first fetch all the documents based on the filter condition, update the data and then save all the documents.

5. MongoTemplate

We will do the update in a single database transaction.

Let’s create an interface ItemRepository:

public interface ItemRepository {
    void updateQuantity(String name, float new);
}

We can add as many methods as we need in this interface and provide the implementations in the ItemRepositoryImpl class:

@Component
public class ItemRepositoryImpl implements ItemRepository {

    @Autowired
    MongoTemplate mongoTemplate;
    
    public void updateQuantity(String name, float new) {
        Query query = new Query(Criteria.where("name").is(name));
        Update update = new Update();
        update.set("quantity", new);
        
        UpdateResult result = mongoTemplate.updateFirst(query, update, Item.class);
        
        if(result == null)
            System.out.println("No documents updated");
        else
            System.out.println(result.getModifiedCount() + " document(s) updated..");

    }

}

Since MongoTemplate is @Autowired, Spring will inject the object dependency. In addition, @Component annotation will allow Spring itself to detect the ItemRepository interface.

The next step is to call this method from our service class to test:

    @Autowired
    ItemRepository itemRepo;

Next, write the method in the service class that calls our customRepo method:

public void updateQuantity(String name, float new) {
    System.out.println("Updating quantity for " + name);
    itemRepo.updateQuantity(name, new);
}

When you invoke, you can see the result:

Updating quantity for Rice
1 document(s) updated..

6. Conclusion

To sum up, we have learned the differences between MongoRepository vs MongoTemplate.

Leave a Reply

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