4

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"?

Harshana
  • 7,297
  • 25
  • 99
  • 173

3 Answers3

9

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

Karthikeyan
  • 2,634
  • 5
  • 30
  • 51
Roman Lapin
  • 173
  • 1
  • 6
  • 2
    https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/index.html#repositories.single-repository-behavior 9.6. Custom Implementations for Spring Data Repositories – Languoguang Apr 02 '21 at 09:45
  • 2
    No possible way to do it by writing a query in a `@Query` annotated method in repository? – Philippe Gioseffi Oct 08 '22 at 18:08
0

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.

Rahul Raj
  • 3,197
  • 5
  • 35
  • 55
-3

I found com.mongodb.MongoClient to achieve the above

Harshana
  • 7,297
  • 25
  • 99
  • 173