【问题标题】:org.springframework.dao.DataIntegrityViolationException: Cannot create fieldorg.springframework.dao.DataIntegrityViolationException:无法创建字段
【发布时间】:2020-08-09 10:29:57
【问题描述】:

Spring-boot更新Mongodb抛出异常,代码如下。

例外

org.springframework.dao.DataIntegrityViolationException: Cannot create field

更新查询

Query queryTwo = new Query();
queryTwo.addCriteria(Criteria.where("customerDetail.CID_18").exists(true));
Update update = new Update();
update.set("customerDetail.CID_18.activeDevices", "900");
    

数据库中的数据如下所示

{
    "_id" : "3c02a683-4601-419b-a598-9e9d8ce57fd0",
    "profileId" : "308",
    "name" : "resellerSent",
    "email" : "resellerSent@gmail.com",
    "customerDetail" : [ 
        {
            "CID_18" : {
                "customerId" : NumberLong(18),
                "activeDevices" : "0",
             
                "_class" : "com.demo.CustomerDetail"
            },
            "CID_2196" : {
                "customerId" : NumberLong(2196),
                "activeDevices" : "5",        
                "_class" : "com.demo.CustomerDetail"
            },
            "CID_2197" : {
                "customerId" : NumberLong(2197),
                "activeDevices" : "0",
                "_class" : "com.demo.CustomerDetail"
            }
        }
    ],
    "_class" : "com.demo.ResellerProfile"
}

我正在使用spring-boot-starter-data-mongodbversion: '2.3.1.RELEASE'

【问题讨论】:

  • 如果您的回答对您有帮助,请勾选并投票以帮助寻求此类问题的人

标签: mongodb criteria


【解决方案1】:

customerDetail是一个数组,所以需要使用位置操作符。

Query query=Query.query(Criteria.where("customerDetail.CID_18").exists(true));
Update update=new Update().set("customerDetail.$[].CID_18.activeDevices", "900");
return mongoTemplate.updateFirst(query,update,Users.class);

如果只为 positional-all 添加$[],则更新将应用于 ALL 满足更新条件的对象。如果你需要更新一个特定的对象,那么你可以使用filterArray()其中setFilter array

请参考Positiaonal-all

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    相关资源
    最近更新 更多