Eternal_Explorer
Eternal_Explorer

Reputation: 1155

Spring data MongoTemplate update nested array failing

The JSON is like below:

{   
"_id" : ObjectId("5e01d02b0e3cfd2e4c5976f0"),
"name" :"SomeName",
"outerEntity" : {
        "accounts" : [
            {
                "accountId" : "1235",
                "type" : "SB",

                "details" : [
                    {
                        "name" : "accountName",
                        "value" : "accName"
                    },
                    {
                        "name" : "ifsc",
                        "value" : "ICICI12122",

                    },

                   {
                        "name" : "address",
                        "value" : "address1",

                    }
                ]
            }
        ],
        "profiles" : null,
        "orders" : null,

      }
}

I am trying to update the fields using the Mongotemplate update like below.But the update is not happening.

 Update data = new Update();

data.set("outerEntity.accounts.$.type", "somevalue");

for each object of details, only update the value

data.set("outerEntity.accounts.details.$.value","someValue");   


Query query = new Query();
                query.addCriteria(Criteria.where("name").is("SomeName"));


mongoTemplate.updateFirst(query, update, UserDetails.class);

Upvotes: 0

Views: 894

Answers (1)

Ashish Bakwad
Ashish Bakwad

Reputation: 811

You can do this using the following way at the application level

Query query = new Query();

query.addCriteria(Criteria.where("name").is("SomeName"));

UserDetails details = mongoTemplate.findOne(query, UserDetails.class);

for(Account acc: details.outerEntity.accounts) {

   for(Account.Detail detail : acc.details) {

      detail.value = "someValue";

   }

}
mongoTemplate.save(details);

Upvotes: 2

Related Questions