Search code examples
mongodbspring-data-mongodb

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

Solution

  • 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