Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data MongoDB update multiple fields

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.

like image 781
jchrbrt Avatar asked Jun 25 '18 14:06

jchrbrt


People also ask

How do I update multiple fields in MongoDB?

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.

How do you update an array of objects in MongoDB?

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.

Which operator is used to update specific fields in MongoDB?

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.


2 Answers

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.

like image 76
pvpkiran Avatar answered Nov 23 '22 23:11

pvpkiran


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);
like image 29
DCO Avatar answered Nov 23 '22 23:11

DCO