Reputation: 39
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.
Upvotes: 1
Views: 131
Reputation: 1352
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}")
)
)
);
Upvotes: 1