BSM
BSM

Reputation: 183

Spring Data - How to write MongoRepository method for findAndModify operation?

I have used findAndModify method of MongoTemplate as below,

 public Organization findAndModifyOrganization(Integer orgId, String name, Integer empId)
{
    Query query = new Query();
    query.addCriteria(Criteria.where("employees.id").is(empId));
    query.addCriteria(Criteria.where("id").is(orgId));

    Update update = new Update();
    update.set("employees.$.name", name);
    Organization org = mongoTemplate.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Organization.class);

    return org;
} 

//class structure

@Document
public class Organization {
    private Integer id;
    private List<Employee> employees;
}

@Document
public class Employee {
    private Integer id;
    private String name;
}

I want to achieve the above using Spring Data MongoRepository method. Please tell me how to update the employee's name using MongoRepository method.

Upvotes: 5

Views: 3684

Answers (1)

Markus Hettich
Markus Hettich

Reputation: 574

As I see it is not possible in a elegant way. The concept of repositories seems to be more general with the background to support different databases.

If you need the full flexibility you could do without the feature of repositories that are generated by spring and use your own implementation. You could also create a own base class for your repositories that helps you to reuse often needed functions. In Spring-Data-MongoDB you can find the class org.springframework.data.mongodb.repository.support.SimpleMongoRepository that you can use as starting point.

Also see the answers in this thread: What's the difference between Spring Data's MongoTemplate and MongoRepository?

Upvotes: 1

Related Questions