How to update a particular field in mongo db collection by using MongoRepository Interface in spring?
Asked
Active
Viewed 2.7k times
15
-
apart from MongoRepository do you know with any other repository? – Anil Aug 16 '16 at 12:16
-
short answer is NO – Alexey Sviridov Aug 08 '19 at 15:02
-
did you get the solution? – Payal May 01 '20 at 09:07
2 Answers
9
You can update specific field by below code:
Query query1 = new Query(Criteria.where("id").is("123"));
Update update1 = new Update();
update1.set("available", false);
mongoTemplate.updateFirst(query1, update1, Customer.class);

Tomerikoo
- 18,379
- 16
- 47
- 61

Ravi Mandli
- 123
- 1
- 4
4
As of today, you can't update the document using MongoRepository
using one query. If you really want to update a particular field using MongoRepository
then following is the steps:
- Fetch the document that you want to update
- Set the new value to a particular field and save that document.
Example:
MyDocument myDocumentToUpdate = myDocumentRepository.findById(documentId); // fetching a document that you want to update the field
myDocumentToUpdate.setMyField(myNewValue); // setting the new value to the field myField
myDocumentRepository.save(myDocumentToUpdate); // saving (It basically updates the document) the updated document

Yubaraj
- 3,800
- 7
- 39
- 57
-
This seems to have the effect of overwriting the entire document rather than just updating the value of that single field. – Paul Springer Sep 01 '20 at 21:53
-
Yes. Internally it is not changing the particular field but as a user, it seems to do so. – Yubaraj Oct 22 '20 at 03:27