Reactive CRUD with `ReactiveMongoRepository`
Oct 2026 · 7 min read
This article builds reactive CRUD for MovieInfo on top of ReactiveMongoRepository and a WebFlux annotated controller, then proves it with WebTestClient against a real MongoDB. The tests show that the id is generated by MongoDB, that PUT replaces fields without upserting, and that a missing id yields 404 via switchIfEmpty. Everything runs on Spring Boot 4.1 with the spring.mongodb.* properties.
Full code: https://github.com/Sch39/java-spring-boot
Problem
Spring MVC controllers translated naively to WebFlux often go wrong in two places: an empty Mono is returned as a 200 with an empty body, and a PUT on a missing id silently creates a new document or fails without a clear status.
Empty Mono is not 404: a
findByIdthat finds no document completes theMonowithout a value, and the HTTP status does not change by itself.Update becomes upsert:
saveon an entity with an id inserts when the document does not exist yet, so a PUT without a check creates new data.
Outcome
Readers will be able to:
Set up a Boot 4 project with
spring-boot-starter-data-mongodb-reactiveand thespring.mongodb.*properties.Map a document with
@Documentand@Id, then useReactiveMongoRepositoryfrom service through controller.Turn an empty
Monointo 404 viaswitchIfEmpty, and prevent a PUT from becoming an upsert.
Implementation
Folder Structure
|compose.yaml
|movies-info-service/
├── build.gradle
└── src/
├── main/
│ ├── java/dev/sch39/movies_info_service/
│ │ ├── MoviesInfoServiceApplication.java
│ │ ├── MovieInfo.java
│ │ ├── MovieInfoRepository.java
│ │ ├── MovieInfoService.java
│ │ └── MovieInfoController.java
│ └── resources/application.yml
└── test/java/dev/sch39/movies_info_service/
└── MovieInfoControllerTest.javaSetup
Run a local MongoDB via compose-reactive (the tests use the movies_info_test database, separate from movies_info):
compose-reactive.yml:
name: spring-boot-reactive-infra
services:
mongodb:
image: mongo:8.0
container_name: spring-boot-reactive-mongodb
ports:
- "127.0.0.1:27017:27017"
volumes:
- mongodb-data:/data/db
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
volumes:
mongodb-data:The port is bound to 127.0.0.1 because this dev instance has no authentication. Run from the / folder:
docker compose -f compose-reactive.yml up -d --wait mongodbInitialize one project (run from the / folder):
mkdir -p movies-info-service
cd movies-info-service
spring init --build=gradle --type=gradle-project --java-version=21 --group-id=dev.sch39 --artifact-id=movies-info-service --name=movies-info-service --dependencies=webflux,data-mongodb-reactive --extract . \
&& rm src/main/resources/application.properties \
&& printf 'spring:\n application:\n name: movies-info-service\n mongodb:\n host: localhost\n port: 27017\n database: movies_info\nserver:\n port: 8082\n' > src/main/resources/application.yml
# remove the default test so Run Test only contains the article's tests
rm src/test/java/dev/sch39/movies_info_service/MoviesInfoServiceApplicationTests.javaCode Blocks
Block 1: @Document and @Id — the id is generated by MongoDB
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfo.java:
package dev.sch39.movies_info_service;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public record MovieInfo(@Id String movieInfoId, String name, Integer year, List<String> cast) {
}Purpose: Map the record to a MongoDB collection so that a null movieInfoId is filled with an ObjectId on save.
Block 2: ReactiveMongoRepository — CRUD without an implementation
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoRepository.java:
package dev.sch39.movies_info_service;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface MovieInfoRepository extends ReactiveMongoRepository<MovieInfo, String> {
}Purpose: Get save, findById, findAll, and deleteById returning Mono/Flux from a single interface.
Block 3: Service — update via findById then save
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoService.java:
package dev.sch39.movies_info_service;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class MovieInfoService {
private final MovieInfoRepository repository;
public MovieInfoService(MovieInfoRepository repository) {
this.repository = repository;
}
public Mono<MovieInfo> add(MovieInfo movieInfo) {
return repository.save(movieInfo);
}
public Flux<MovieInfo> findAll() {
return repository.findAll();
}
public Mono<MovieInfo> findById(String id) {
return repository.findById(id);
}
public Mono<MovieInfo> update(String id, MovieInfo movieInfo) {
return repository.findById(id)
.map(existing -> new MovieInfo(id, movieInfo.name(), movieInfo.year(), movieInfo.cast()))
.flatMap(repository::save);
}
public Mono<Void> delete(String id) {
return repository.deleteById(id);
}
}Purpose: Ensure update only calls save when the document exists, so a missing id yields an empty Mono instead of an insert.
Block 4: Controller — an empty Mono becomes 404
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoController.java:
package dev.sch39.movies_info_service;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/v1/movie-info")
public class MovieInfoController {
private final MovieInfoService service;
public MovieInfoController(MovieInfoService service) {
this.service = service;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<MovieInfo> add(@RequestBody MovieInfo movieInfo) {
return service.add(movieInfo);
}
@GetMapping
public Flux<MovieInfo> findAll() {
return service.findAll();
}
@GetMapping("/{id}")
public Mono<ResponseEntity<MovieInfo>> findById(@PathVariable String id) {
return service.findById(id)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
}
@PutMapping("/{id}")
public Mono<ResponseEntity<MovieInfo>> update(@PathVariable String id, @RequestBody MovieInfo movieInfo) {
return service.update(id, movieInfo)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public Mono<Void> delete(@PathVariable String id) {
return service.delete(id);
}
}Purpose: Map POST to 201, DELETE to 204, and an empty Mono from GET/PUT to 404 with map + switchIfEmpty.
Test Blocks
Test 1: POST then GET — MongoDB creates the id
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoControllerTest.java:
package dev.sch39.movies_info_service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = "spring.mongodb.database=movies_info_test")
@AutoConfigureWebTestClient
class MovieInfoControllerTest {
private static final String URL = "/v1/movie-info";
@Autowired
private WebTestClient client;
@Autowired
private MovieInfoRepository repository;
@BeforeEach
void cleanCollection() {
repository.deleteAll().block();
}
@Test
void createThenFindById() {
MovieInfo saved = client.post().uri(URL)
.bodyValue(new MovieInfo(null, "Batman Begins", 2005, List.of("Christian Bale")))
.exchange()
.expectStatus().isCreated()
.expectBody(MovieInfo.class).returnResult().getResponseBody();
assertNotNull(saved.movieInfoId(), "id must be generated by MongoDB");
MovieInfo found = client.get().uri(URL + "/{id}", saved.movieInfoId())
.exchange()
.expectStatus().isOk()
.expectBody(MovieInfo.class).returnResult().getResponseBody();
System.out.println("saved=" + saved);
System.out.println("found=" + found);
assertEquals(saved, found, "found vs saved");
}Purpose: Prove that POST returns 201 with an id generated by MongoDB and that GET with that id returns the same document.
Test 2: PUT replaces fields and keeps the id
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoControllerTest.java:
@Test
void updateReplacesFieldsAndKeepsId() {
MovieInfo saved = repository.save(new MovieInfo(null, "Dark Knight", 2007, List.of("Heath Ledger"))).block();
MovieInfo updated = client.put().uri(URL + "/{id}", saved.movieInfoId())
.bodyValue(new MovieInfo(null, "The Dark Knight", 2008, List.of("Heath Ledger")))
.exchange()
.expectStatus().isOk()
.expectBody(MovieInfo.class).returnResult().getResponseBody();
System.out.println("updated=" + updated);
System.out.println("count=" + repository.count().block());
assertEquals(saved.movieInfoId(), updated.movieInfoId(), "id must stay the same");
assertEquals(2008, updated.year(), "year");
assertEquals(1L, repository.count().block(), "document count");
}Purpose: Prove that PUT overwrites fields on the same document without adding a new document.
Test 3: DELETE, then a missing id yields 404
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoControllerTest.java:
@Test
void deletedIdReturnsNotFound() {
MovieInfo saved = repository.save(new MovieInfo(null, "Inception", 2010, List.of("Leonardo DiCaprio"))).block();
client.delete().uri(URL + "/{id}", saved.movieInfoId()).exchange().expectStatus().isNoContent();
System.out.println("count after delete=" + repository.count().block());
client.get().uri(URL + "/{id}", saved.movieInfoId()).exchange().expectStatus().isNotFound();
client.put().uri(URL + "/{id}", saved.movieInfoId())
.bodyValue(new MovieInfo(null, "Inception", 2010, List.of("Leonardo DiCaprio")))
.exchange().expectStatus().isNotFound();
assertEquals(0L, repository.count().block(), "PUT on a missing id must not upsert");
}
}Purpose: Prove that DELETE returns 204 and that GET or PUT on an id that no longer exists returns 404 without creating a new document.
Run Test
Run from the movies-info-service/ folder:
./gradlew cleanTest test -iOutput:
...
> Task :test
MovieInfoControllerTest > updateReplacesFieldsAndKeepsId() STANDARD_OUT
updated=MovieInfo[movieInfoId=6ae37477b372c7f79e8a4293, name=The Dark Knight, year=2008, cast=[Heath Ledger]]
count=1
MovieInfoControllerTest > deletedIdReturnsNotFound() STANDARD_OUT
count after delete=0
MovieInfoControllerTest > createThenFindById() STANDARD_OUT
saved=MovieInfo[movieInfoId=6ae37478b372c7f79e8a4295, name=Batman Begins, year=2005, cast=[Christian Bale]]
found=MovieInfo[movieInfoId=6ae37478b372c7f79e8a4295, name=Batman Begins, year=2005, cast=[Christian Bale]]
Generating HTML test report...
...
BUILD SUCCESSFUL in 14s
5 actionable tasks: 2 executed, 3 up-to-date
Consider enabling configuration cache to speed up this build: https://docs.gradle.org/9.8.2/userguide/configuration_cache_enabling.htmlWhy It Works
@Document and @Id: @Document maps the type to a MongoDB collection, and a String field annotated with @Id is filled with an ObjectId by MongoDB when save is called with a null id. The output shows movieInfoId=6ae37478b372c7f79e8a4295, created by the server rather than the application.
ReactiveMongoRepository: this interface returns Mono for single-document operations and Flux for multiple documents, so no thread waits on I/O. Spring Data creates the implementation at startup (log Found 1 Reactive MongoDB repository interface).
Empty Mono and switchIfEmpty: findById for a missing id completes the Mono without a value, so map(ResponseEntity::ok) never runs and switchIfEmpty supplies the 404. In update, an empty findById also skips flatMap(repository::save), which is what prevents the upsert.
Edge Cases
PUT on a missing id: yields 404 and the document count stays 0 (PUT on a missing id must not upsert). Calling save directly with the id from the path would insert a new document.
Body without an id: the id in the body is ignored by update; the id always comes from the path, so a client cannot move a document to another id via the body.
.block() in tests: used in @BeforeEach and data setup because the test thread is not the event loop thread. Do not copy this pattern into main code.
Trade-offs
Strategy | Pro | Con |
|---|---|---|
| Almost no code, queries derived from method names | Complex queries and partial updates are limited |
| Full control over | More verbose, no ready-made methods |
| Easy to read, natural 404 for missing ids | Two round trips and prone to races between two updates |
Best practice: start with ReactiveMongoRepository, and move to ReactiveMongoTemplate only when you need atomic or partial updates.
Gotchas I Hit
Forgetting
import org.springframework.http.HttpStatus;produced four errors, among themcannot find symbol ... variable HttpStatuson@ResponseStatus(HttpStatus.CREATED)andan enum annotation value must be an enum constant. The second message is only a consequence of the first.In Boot 4 the
@AutoConfigureWebTestClientannotation lives inorg.springframework.boot.webtestclient.autoconfigure, and the tests need the companion startersspring-boot-starter-data-mongodb-reactive-testandspring-boot-starter-webflux-testadded byspring init.A
PUTon an already-deleted id returns 404 and the document count stays0, because an emptyfindByIdskipsflatMap(repository::save).
Production Checklist
Do the tests use a database separate from real data? Set a test-specific
spring.mongodb.databasebefore callingdeleteAll().Are MongoDB credentials in the repo? Move them to environment variables or
spring.mongodb.urifrom a secret.Can the update endpoint be called concurrently on the same document? Consider
@Versionor atomic updates viaReactiveMongoTemplate.
References
Spring Boot, MongoDB (
spring.mongodb.*): https://github.com/spring-projects/spring-boot/blob/v4.1.0/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/data/nosql.adocSpring Data MongoDB, Reactive repository query methods: https://github.com/spring-projects/spring-data-mongodb/blob/main/src/main/antora/modules/ROOT/pages/mongodb/repositories/query-methods.adoc
Spring Data MongoDB, Template CRUD operations: https://github.com/spring-projects/spring-data-mongodb/blob/main/src/main/antora/modules/ROOT/pages/mongodb/template-crud-operations.adoc