Harshana
Harshana

Reputation: 7647

Custom method for update query with spring data MongoRepository

I am using org.springframework.data.mongodb.repository.MongoRepository. I have written some custom method like below,

public interface DocRepository extends MongoRepository<Doc, String> {
     Doc findByDocIdAndAssignmentId(final String docId, final String assignemtId);
}

How can I write a custom method which update all entries when meeting a criteria.

For example set document tilte field to "abc" if assignment id is "xyz"?

Upvotes: 4

Views: 11509

Answers (3)

Roman Lapin
Roman Lapin

Reputation: 173

1) You need to create inteface e.g CustomDocRepository and add this interfaces as Base for your DocRepository:

public interface DocRepository extends MongoRepository<Doc, String>, CustomDocRepository {

    void updateDocumentTitle(String id, String title);

}

2) You need to add implementation for the DocRepository:

@Repository
public class CustomDocRepositoryImpl implements DocRepository {
  @Autowired
  private MongoTemplate mongoTemplate;


@Override
public void updateDocumentTitle(String id, String title) {
    Query query = new Query().addCriteria(where("_id").is(id));

    Update update = new Update();
    update.set("title", title);
    mongoTemplate.update(Doc.class).matching(query).apply(update).first();
}
}

That is all you need to do

Upvotes: 9

Harshana
Harshana

Reputation: 7647

I found com.mongodb.MongoClient to achieve the above

Upvotes: -3

Rahul Raj
Rahul Raj

Reputation: 3459

Provided you have an autowired attribute mongoTemplate in your service class. Add the below code to update the document.

Query query = new Query();
query.addCriteria(Criteria.where("assignmentId").is("xyz"))
Update update = new Update();
update.set("title", "abc");
mongoTemplate.updateFirst(query, update, Doc.class);

You dont need to have findByDocIdAndAssignmentId for the update purpose.

Upvotes: 0

Related Questions