VitalyT
VitalyT

Reputation: 1691

How update nested Document in MongoDB preferred of using Spring Data Java

I'm trying to update all the null "role" property in the nested mongo document as the following:

 {
            "id": "5a46ae611331fb6b8254a271",
            "name": "my_Customer",
            "users": [
                {
                    "lastName": "ZoozFirstNameUser",
                    "firstName": "ZoozLastNameUser",
                    "id": "5a46ae611331fb6b8254a26e",
                    "role": null
                },
                {
                    "lastName": "Vitaly",
                    "firstName": "Treck",
                    "id": "5a46ae611331fb6b8254a26f",
                    "role": null
                }
            ]
    }

I'm trying to do it with the following command but it not working:

     @Override
          public int updateUserRole(Role newRole) {

                  Query query = Query.query(Criteria.where("users")
                            .elemMatch(Criteria.where("role").is(null)));

                  Update update = new Update().set("users",                      
                           new BasicDBObject("role", newRole));

             return mongoTemplate.updateMulti(query, update, Customer.class).getN();
         }

I got no errors but nothing is changed after this command...:(

Please help

Upvotes: 1

Views: 2080

Answers (1)

pvpkiran
pvpkiran

Reputation: 27048

Try this update statement

Update update = new Update().set("users.$.role", newRole);

Upvotes: 2

Related Questions