Spring Data MongoRepository Interface Methods Example


In this article, we’ll explore the methods available in the MongoRepository interface provided by Spring Data in the package org.springframework.data.mongodb.repository. MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extends the CrudRepository interface.

Spring Boot and MongoDB

MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.

public interface MongoRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>{}

where:

T is replaced by the document POJO class e.g. Person, Employee, etc.

ID is the data type used for id in the POJO class e.g. String, Long, Integer.

There are only two new methods introduced in the MongoRepository interface and the rest are inherited from the CrudRepository interface.

1. insert(S entity)

insert(S entity) method is used to save/persist the data into the MongoDB database and return the instance of save the entity.

Method signature:

<S extends T> S insert(S entity);

Example:

School school= new School("Delhi Public1 School", 1998, new String[]{"Science", "Art"}, 600);
         
schoolRepository.insert(school);

2. insert(Iterable<S> entities)

insert(Iterable<S> entities) method is used to save the list of entities/documents in the MongoDB database at once.

Method signature:

<S extends T> List<S> insert(Iterable<S> entities);

Example:

List<School> schools = Arrays.asList(
		new School("Delhi Public1 School", 1998, new String[]{"Science", "Art"}, 600),
        new School("Mumbai Public School", 1995, new String[]{"Science"}, 450),
        new School("Jaipur Public School", 2002, new String[]{"Science", "Art", "Commerce"}, 755),
        new School("Kolkata Public School", 1995, new String[]{"Art"}, 300)
);

schoolRepository.insert(schools);

References

  1. Interface MongoRepository<T,ID>
  2. Spring Data CrudRepository Interface Example
  3. Spring Data JPA Derived Query Methods Example

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.