gaurav9620
gaurav9620

Reputation: 1197

update multiple documents in mongodb from spring mongo

In my use case I want to update multiple documents at once, documents that match a query, using spring-data-mongo.

Here is what I have been trying,

Criteria filterCriteria = new Criteria().andOperator(Criteria.where("bac").is("def"));
        Update update = new Update();
        update.set("status", status);
        Query query = new Query();
        query.addCriteria(filterCriteria);
        mongoOperations.findAndModify(query, update, MyClass.class);

But this is not updating any document.

Plus I have looked up in the mongo documentation but have not anything useful https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#comparisons-with-the-update-method

Here is the version that I am using

  1. Mongodb - 3.6
  2. spring-data-mongodb - 1.5.5.RELEASE

Upvotes: 3

Views: 9820

Answers (2)

salerokada
salerokada

Reputation: 383

@Autowire
MongoTemplate mongoTemplate;

Query query = new Query();
Criteria filterCriteria = Criteria.where("bac").is("def");
query.addCriteria(filterCriteria);
Update update = new Update();
update.set("status", status);
mongoTemplate.updateMulti(query, update, MyClass.class);

Upvotes: 1

Sahil Sharma
Sahil Sharma

Reputation: 164

findAndModify(...) method can update a document and return either the old or newly updated document in a single operation.

To update all document that matches the given query use updateMulti(...).

https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#updateMulti-org.springframework.data.mongodb.core.query.Query-org.springframework.data.mongodb.core.query.UpdateDefinition-java.lang.Class-

visit the link and there you will find it.

enter image description here

Upvotes: 3

Related Questions