Is it possible with Spring-Data-MongoDB to update multiple fields of a document with one query.
For example, I can run this mongo query:
db.customers.update(
{"firstname": "Max"},
{
$set: {
"lastname": "Maier",
"email": "[email protected]"
}
}
);
How can we achieve this with code and the spring MongoTemplate? For example here is the code to udpate one value:
Query select = Query.query(Criteria.where("firstname").is("Max"));
Update updateValue = Update.update("lastname", "Maier");
UpdateResult updateResult = mongoTemplate.updateFirst(select, updateValue, Customer.class);
It seems that the Update#set method accepts only one (key, value) and no multi-values or list of values.
Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.
Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.
Comparing values (or numbers) using $max operator: Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 40000.
It seems that the Update#set method accepts only one (key, value) and no multi-values or list of values.
Yes, it accepts only one key and value at a time. But you can do that for many keys and values as you want. It is like a Map, you can add as many keys(unique) and values as you like.
You just need to extend your code a bit
Query select = Query.query(Criteria.where("firstname").is("Max"));
Update update = new Update();
update.set("lastname", "Maier");
update.set("email", "[email protected]");
UpdateResult updateResult = mongoTemplate.findAndModify(select, update, Customer.class);
If you dig deep into findAndModify
method, you can understand, behind the scenes it is holding a key value map.
In my version findAndModifiy does not return UpdateResult. I had to use method updateMulti
Query select = Query.query(Criteria.where("firstname").is("Max"));
Update update = new Update();
update.set("lastname", "Maier");
update.set("email", "[email protected]");
UpdateResult updateResult = mongoTemplate.updateMulti(select, update, Customer.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With