1

I tried to modify array values with following :

        final UpdateResult ur = operations.updateMulti(
                new Query().addCriteria(
                        Criteria.where("tags.applications").in(Collections.singletonList(4))),
                new Update().set(String.format("%s.$","tags.applications"), 8),
                "testMetaModel");

the problem is, if the array is like tag: application: [1,2,3,4,4,5,6] If I use above "$" update, it could only update the first matched "4", but I want to update all "4" to "8", what should I do ? I use spring MongoTemplate.

1

1 Answer 1

1

I have used the positional filters, refer here.

shell query:

db.demo.update(
  {},
  {
    $set:{
      "a.$[element]":8
    }
  },
  {
    arrayFilters:[
      {
        "element":4
      }
    ]
  }
)

This will update all the matched elements in the provided array.

The above shell query is working fine. you can integrate it with your spring data. I tried to add that in springdata but fix it according to the shell query I provided if any issue is faced. :)

Update update=new Update().set("tags.applications.$[element]", 8).filterArray(Criteria.where("element").is(4)); 
final UpdateResult ur = operations.updateMulti(
        new Query(),
        update,
        "testMetaModel");

Update

Java driver query:

db.getCollection("demo").updateMany(
        new Document(),
        new Documen("$set", new Document("a.$[element]", 8)),
        new UpdateOptions().arrayFilters(
            Arrays.asList( 
            Document.parse("{'element': 4}")
            )
        )
);
Sign up to request clarification or add additional context in comments.

3 Comments

It seems that I don't have the method: "update.filterArray(Criteria.where("element")." ? what could be done
seems like spring data does not have UpdateOptions. you can use java driver to update the document. please refer this stackoverflow.com/a/55503265/8383549
I have updated my answer with the java driver query. hope this will help you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.