Anil
Anil

Reputation: 223

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

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

Upvotes: 18

Views: 30916

Answers (2)

Yubaraj
Yubaraj

Reputation: 3988

You can't update particular field in document using MongoRepository, because MongoRepository overwrites whole document. You should use MongoTemplate, as explained in other answer.

However, if you really want to update a particular field using MongoRepository, then:

  1. Fetch whole document that you want to update
  2. Set the new value to a particular field
  3. Save whole document.

Example:

MyDocument myDocumentToUpdate = myDocumentRepository.findById(documentId);
myDocumentToUpdate.setMyField(myNewValue);
myDocumentRepository.save(myDocumentToUpdate);

Upvotes: 6

Ravi Mandli
Ravi Mandli

Reputation: 131

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);

Upvotes: 9

Related Questions