Spring Data MongoDBmedium3-5 years

A `Product` collection embeds a `List<String> tags` via Spring Data MongoDB's `@Document` mapping, and a service does `product.getTags().add("sale")` then relies on a later `repository.save(product)` to persist it. It works in a quick manual test but a code reviewer flags it as fragile. What's the actual risk, and how would you make the write explicit and safe?

repository.save(product) does a whole-document replace — it writes every field of product back to the database as it currently is in memory, not just the tags field that actually changed. That works in the quick test because nothing else touched the document in between, but it means the code is implicitly relying on the in-memory product object being a fully up-to-date copy of everything in the stored document at the moment of the save; if anything else updated a different field on the same document between the read and this save, that other field's change gets silently overwritten back to its stale, in-memory value. The safer, explicit alternative is a targeted update — MongoTemplate with Update.push("tags", "sale") — which writes only the tags field and never touches, or overwrites, anything else in the document.

The lesson behind it →