Quick revision
The short answer
We build a Query that matches the article by _id, an Update that combines $inc on views with $addToSet on tags, and call mongoTemplate.findAndModify() with FindAndModifyOptions.options().returnNew(true). MongoDB applies both changes in one atomic server-side operation and returns the document as it is after the update, so no concurrent request can slip in between reading and writing.
What to remember
In this answer, we wrote a MongoTemplate method that matches the article by _id, uses an Update with inc("views", 1) and addToSet("tags", tag), and calls findAndModify() with returnNew(true) to get the updated document. Because MongoDB applies the whole update to one document atomically on the server, concurrent requests never lose an increment. We also saw why reading, changing and saving the object in Java loses updates, and why a repository save() is worse because it overwrites the whole document.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We build a Query that matches the article by _id, an Update that combines $inc on views with $addToSet on tags, and call mongoTemplate.findAndModify() with FindAndModifyOptions.options().returnNew(true). MongoDB applies both changes in one atomic server-side operation and returns the document as it is after the update, so no concurrent request can slip in between reading and writing.
Why this question is asked
Counters and tag lists look trivial, and that is why they are a classic source of lost updates. If two requests load the same article, each adds one to views in Java and saves it, one increment disappears. Interviewers ask this to see whether we know that MongoDB can do the change itself, on the server, and whether we know the Spring Data API for it. In this answer, we will recap the update operators involved, write the code, see why it is atomic, look at the broken read-modify-write version and see why a repository save() makes it worse.
1A Quick Recap of $inc and $addToSet
MongoDB updates are described by operators instead of whole documents. $inc adds a number to a field, creating the field with that number if it is missing. $addToSet adds a value to an array only if the array does not already contain it, so it behaves like adding to a set. Both run inside the database, on the current version of the document, at the moment the update is applied.
MongoTemplate is Spring Data MongoDB's central class for talking to the database. Where a repository gives us methods such as save() and findById(), MongoTemplate lets us send exactly the query and update we want. The Query and Criteria classes describe which documents match, and the Update class collects update operators.
2Writing the Code With MongoTemplate
Here is the whole method. It finds the article by id, applies both operators, and returns the updated document.
Notice three details. Criteria.where("_id").is(id) lets Spring convert the String id to an ObjectId when the id field is mapped that way. The Update chains both operators into one update document. And returnNew(true) asks for the document after the update; without it, findAndModify() returns the version before the change, which surprises many people the first time.
If nothing matches the id, findAndModify() returns null. If we wanted to create the article on first view, we could add .upsert(true) to the options, but for articles that should already exist, null is the honest signal that the id was wrong.
3Why This Is Atomic
MongoDB guarantees that a write to a single document is atomic. The server locks that one document, applies all the operators in the update, writes the result and only then lets another write to the same document proceed. So if 50 requests call viewAndTag() at the same moment, the server applies them one after another, and views goes up by exactly 50.
The reason our Java code is safe is that it never reads the value and decides on a new one. It sends an instruction, add one, and the server works it out on whatever the current value is. There is no window between a read and a write for another request to use.
6 messages in order. Play them, or step through them one at a time.
The server serialises the two updates on the document, so no increment is lost.
4The Broken Version: Read, Modify, Save
Compare it with the version many people write first, using a repository.
The trouble is the gap between findById() and save(). Both requests read 100, both compute 101, and both write 101. But there is a second, worse problem. save() of an existing document replaces the whole document with the Java object. If another request changed the title or added a different tag in between, save() writes back our old copy and silently erases that change too. So read-modify-write in Java loses not only increments but any concurrent change to the document.
We could protect the repository version with a @Version field and optimistic locking, which would turn the lost update into an exception and a retry. For a counter that is wasted effort: the atomic operator needs no version check and never conflicts.
5Follow-up questions
When would we use updateFirst() instead of findAndModify()?
When we do not need the document back. mongoTemplate.updateFirst(q, u, Article.class) sends the same atomic update and returns an UpdateResult with the matched and modified counts. It is slightly cheaper because the server does not return the document, which is ideal for a page-view counter where the caller only needs to know it worked.
Is this atomic across two documents?
No. The single-document guarantee covers one document only. If we had to increment an article and an author's total together and keep them consistent, we would need a multi-document transaction, which MongoDB supports on replica sets, or a design where one document holds both values.
What if tags must stay sorted or limited to ten entries?
$addToSet does not sort or limit. We could use $push with $each, $sort and $slice to keep a bounded sorted array, but $push does not check for duplicates, so we would add a filter that the tag is not already present, for example Criteria.where("tags").ne(tag), to keep the set behaviour.
6Conclusion
In this answer, we wrote a MongoTemplate method that matches the article by _id, uses an Update with inc("views", 1) and addToSet("tags", tag), and calls findAndModify() with returnNew(true) to get the updated document. Because MongoDB applies the whole update to one document atomically on the server, concurrent requests never lose an increment. We also saw why reading, changing and saving the object in Java loses updates, and why a repository save() is worse because it overwrites the whole document.
Open with
I would do it in a single server-side update with MongoTemplate. I build Query.query(Criteria.where("_id").is(id)), then an Update with new Update().inc("views", 1).addToSet("tags", tag), and call mongoTemplate.findAndModify(q, u, FindAndModifyOptions.options().returnNew(true), Article.class). returnNew(true) matters because by default findAndModify returns the document as it was before the update.
Then, if they want more
This is atomic because MongoDB applies all operators of an update to one document as a single operation, and the server computes the new value from whatever the current value is, so concurrent calls are applied one after another and none is lost. addToSet only adds the tag if it is not already in the array, so repeated calls are safe.
What I would avoid is loading the document through the repository, incrementing in Java and calling save(). Two requests can read the same value and both write the same result, and save() replaces the whole document, so it can also erase other fields that someone changed in between.
If I did not need the document back, I would use updateFirst with the same update, which just returns the matched and modified counts.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- MongoDB manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Using MongoTemplate in Spring Data MongoDB, write code that atomically increments the...": https://scrivio-interview-library.netlify.app/databases/mongodb/df448816a6/