How to use SpringData MongoRepository to interact with MongoDB

How to use SpringData MongoRepository to interact with MongoDB

In the past post, we had learned how to work with MongoDB by MongoOperations which supports a set of standard APIs to manipulate data. So in the tutorial, JavaSampleApproach will show a powerful tool SpringData MongoRepository with flexible and more complex APIs to interact with MongoDB.

Related articles:
Spring MongoOperations to access MongoDB
How to build SpringBoot MongoDb RestfulApi
SpringData MongoDB GridFsTemplate to save, retrieve, delete binary files (Image, Text files)
Angular 4 + Spring Boot + MongoDB CRUD example
Spring Boot + Angular 6 example | Spring Data + REST + MongoDb CRUD example

I. Technologies

– Java: 1.8
– Maven: 3.3.9
– Spring Tool Suite: Version 3.8.4.RELEASE
– Spring Boot: 1.5.4.RELEASE
– MongoDB: v3.4.1

I. MongoRepository

MongoRepository is implemented with lots of APIs to store and retrieve data. We can use MongoRepository with full generic CRUD operations of CrudRepository interface, and additional methods of PagingAndSortingRepository interface for pagination and sorting.
MongoRepository also extends QueryByExampleExecutor so it allows execution of Query by Example.

public interface MongoRepository
		extends PagingAndSortingRepository, QueryByExampleExecutor {

public interface PagingAndSortingRepository extends CrudRepository {

-> With a strong set of APIs, We should start Spring MongoRepository to manipulate data from MongoDB.

SpringData Mongodb - architectures c

II. Practice

We create a SpringBoot project that uses MongoRepository to store and retrieve data from MongoDB.

SpringData Mongodb - project structure

Step to do:
– Create SpringBoot project
– Create Customer document
– Implement Customer MongoRepository
– Implement Client
– Deployment

1. Create SpringBoot project

Using Spring Tool Suite to create a Spring Starter Project, then add dependency {data-mongodb}:


2. Create Customer document

Create a simple Customer document:

package com.javasampleapproach.datamongodb.model;


public class Customer {
	private String id;
	private String name;
	private int age;
	public Customer(String name, int age){ = name;
		this.age = age;
	public void setName(String name){ = name;
	public String getName(){
	public void setAge(int age){
		this.age = age;
	public int getAge(){
		return this.age;
	public String toString(){
		String info = String.format("{'id': %s 'name': %s, 'age': %d}", id, name, age);
		return info;

@Document: identifies a domain object to persisted to MongoDB
@Id: demarcates an identifier.

3. Implement Customer MongoRepository

interface CustomerMongoRepository extends MongoRepository

package com.javasampleapproach.datamongodb.repository;

import java.util.List;


import com.javasampleapproach.datamongodb.model.Customer;

public interface CustomerMongoRepository extends MongoRepository{
	List findByName(String name);

– Open, add configuration to connect with Mongo Server:

4. Implement Client

Use CommandLineRunner to implement a simple client to manipulate data from MongoDB via CustomerMongoRepository:

package com.javasampleapproach.datamongodb;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.javasampleapproach.datamongodb.model.Customer;
import com.javasampleapproach.datamongodb.repository.CustomerMongoRepository;

public class SpringDataMongoDbApplication implements CommandLineRunner{
	CustomerMongoRepository customerRepo;

	public static void main(String[] args) {, args);
	public void run(String... arg0) throws Exception {
		 * Save Entities 
		System.out.println("----------------Save customers!");
		// save an Entity
		Customer peter = new Customer("Peter", 24);;
		// save a List Entity
		List custs = Arrays.asList(new Customer("Mary", 27), new Customer("Lauren", 21), new Customer("Peter", 19));;
		 * Find Entities
		System.out.println("----------------Find customers has name is 'Peter'!");
		List peters = customerRepo.findByName("Peter");
		// -> Show result
		 * Update an Entity
		System.out.println("----------------Rename a customer which has name is 'Peter' to 'Jack'!");
		Customer jack = peters.get(0);
		 * Delete an Entity
		System.out.println("----------------Delete the remain Peter customer!");
		 * Find All customer
		System.out.println("----------------Show All Customers!");
		List customers = customerRepo.findAll();

5. Deployment

Start MongoDB server by commandline: .\MongoDB\Server\3.4\bin>mongod.exe

-> Logs:

2017-06-15T16:53:29.773+0700 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/'
2017-06-15T16:53:29.776+0700 I NETWORK  [thread1] waiting for connections on port 27017

Build and Run the SpringBoot project with commandlines: mvn clean install, mvn spring-boot:run

-> Logs:

----------------Save customers!
----------------Find customers has name is 'Peter'!
{'id': 594260d3c3efb42844911a9a 'name': Peter, 'age': 24}
{'id': 594260d3c3efb42844911a9d 'name': Peter, 'age': 19}
----------------Rename a customer which has name is 'Peter' to 'Jack'!
----------------Delete the remain Peter customer!
----------------Show All Customers!
{'id': 594260d3c3efb42844911a9a 'name': Jack, 'age': 24}
{'id': 594260d3c3efb42844911a9b 'name': Mary, 'age': 27}
{'id': 594260d3c3efb42844911a9c 'name': Lauren, 'age': 21}

Run MongoDB shell by commandline: .\MongoDB\Server\3.4\bin>mongo.exe

-> Logs:

MongoDB shell version v3.4.1
connecting to: mongodb://
MongoDB server version: 3.4.1

Results with MongoDB shell:

SpringData Mongodb - Results

show dbs is used to show all MongoDB databases. -> Having one database jsa_mongodb which is created by the SpringBoot MongoRepository application.
use jsa_mongodb is used to select the jsa_mongodb database to work.
show collections is used to show all collections in current database. -> We just have one collection: {customer}
db.customer.find() is used to query all documents of the collection customer. -> We have 3 customer documents {Jack, Mary, Lauren}

IV. Sourcecode


By grokonez | June 15, 2017.

Last updated on April 9, 2021.

Related Posts

1 thought on “How to use SpringData MongoRepository to interact with MongoDB”

  1. Hi,

    Thanks for the wonderful examples,
    While implementing this i am getting below error :

    The method save(S) in the type CrudRepository is not applicable for the arguments (List)
    on; method because custs is list of customer and it is accepting only customer instance not list of customer.

    Could you please help me here.

Got Something To Say:

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