首页 > 解决方案 > E11000 使用自定义String作为主键时spring数据mongo中重复键错误收集

问题描述

我想在我的集合中使用自定义字符串代码作为主键,并确保Mongo Repository根据代码保存更新/更新文档。但是,当使用相同的代码添加第二个条目时,它会抛出E11000 duplicate key error collection。PFB 我的代码片段:

public class WebCategoryTemp {

@Id
private String code;
@Indexed
private Long timestamp;
private String name;
private String parent;
private Map<String,String> attributes;
private List<String> brands;
private List<String> categories;
private List<String> optionCodes;

}

存储库:

public interface WebCategoryTempRepository extends 
MongoRepository<WebCategoryTemp, String> {
}

我在添加另一个具有相同代码的条目时遇到以下异常:

org.springframework.dao.DuplicateKeyException: E11000 duplicate key error 
  collection: AQUAMAN.webCategoryTemp index: _id_ dup key: { _id: 
  "GlobalTrends" }; nested exception is com.mongodb.MongoWriteException: 
  E11000 duplicate key error collection: AQUAMAN.webCategoryTemp index: _id_ 
  dup key: { _id: "GlobalTrends" }

示例 Mongo 文档:

{
    "_id" : "GlobalTrends",
    "timestamp" : NumberLong("1570439407216"),
    "name" : "GlobalTrendss",
    "parent" : "83",
    "attributes" : {
        "categoryLevel" : "4",
        "returnWindow" : "35",
        "isReturnable" : "true",
        "maximumQuantity" : "2",
        "categoryToggle" : "toggleCode",
        "catalogId" : "rilfnlProductCatalog"
    },
    "brands" : [ ],
    "categories" : [
        "830316001"
    ],
    "version" : NumberLong(0)
}

标签: javamongodbspring-data

解决方案


推荐阅读