Spring Data Reactive MongoDB — CRUD Operations

Project Setup:

Sample Application:

MongoDB Setup:

version: "3"
services:
mongo:
image: mongo
ports:
- 27017:27017
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
mongo-express:
image: mongo-express
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: password

Entity:

@Data
@Document
@ToString
public class Freelancer {

@Id
private String id;
private String name;
private int age;
private List<String> skills;

}

Repository:

  • findBySkillsAll — We might want to search for people with all given skills.
  • findBySkillsIn — We might want to search for people containing 1 of the given skills.
@Repository
public interface FreelancerRepository extends ReactiveMongoRepository<Freelancer, String> {

@Query("{ 'skills': { $all: ?0 } }")
Flux<Freelancer> findBySkillsAll(List<String> skills);

Flux<Freelancer> findBySkillsIn(List<String> skills);

}

Service:

RestController:

  • I directly expose entity class for this demo. In real life you might want to use a DTO.

Application Properties:

spring.data.mongodb.database=admin
spring.data.mongodb.username=admin
spring.data.mongodb.password=password

Demo:

  • Lets start the application.
  • I register few freelancers as shown here using the POST endpoint.
{
"name": "sam",
"age": 40,
"skills": [ "js", "react", "python"]
}

{
"name": "jack",
"age": 38,
"skills": [ "js", "angular", "postgres"]
}

{
"name": "james",
"age": 30,
"skills": [ "java", "reactor", "mongo"]
}

{
"name": "smith",
"age": 32,
"skills": [ "qa", "selenium"]
}
  • GET
  • PUT
  • Search By All skills
  • Search By one of the skills
  • DEL

Summary:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinoth Selvaraj

Vinoth Selvaraj

Principal Software Engineer — passionate about software architectural design, microservices.