Spring数据MongoTemplate更新嵌套数组失败

时间:2019-12-24 10:10:07

标签: java mongodb spring-boot spring-data mongotemplate

JSON如下:

{   
"_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,

      }
}

我正在尝试使用如下所示的Mongotemplate更新来更新字段。但是更新没有发生。

 Update data = new Update();

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

对于每个细节对象,仅更新值

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


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


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

1 个答案:

答案 0 :(得分:2)

您可以在应用程序级别使用以下方式进行操作

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);