How to update particular field in mongo db by using MongoRepository Interface?
Asked Answered
S

2

18

How to update a particular field in mongo db collection by using MongoRepository Interface in spring?

Sherrod answered 16/8, 2016 at 11:3 Comment(3)
apart from MongoRepository do you know with any other repository?Sherrod
short answer is NOMerat
did you get the solution?Gum
S
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);
Sori answered 7/7, 2017 at 19:13 Comment(2)
This method uses MongoOperation, not MongoRepositoryMerat
Not an answer, see the previous commentScholasticism
S
5

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:

  1. Fetch the document that you want to update
  2. 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
Sitin answered 26/6, 2020 at 11:2 Comment(2)
This seems to have the effect of overwriting the entire document rather than just updating the value of that single field.Mohican
Yes. Internally it is not changing the particular field but as a user, it seems to do so.Sitin

© 2022 - 2024 — McMap. All rights reserved.