【问题标题】:Mongodb upsert throwing DuplicateKeyExceptionMongodb upsert 抛出 DuplicateKeyException
【发布时间】:2013-05-04 03:27:09
【问题描述】:

在尝试使用方法 [1] 插入(增加或插入)文档时,我确实会不时收到此错误 [2]。

[1]

public NGram save(final NGram ngram) {
    Criteria cr = where("_id").is(ngram.getNgram())
            .and("f3c").is(ngram.getF3c())
            .and("tokCount").is(ngram.getTokCount())
            .and("first").is(ngram.getFirst())
            ;
    if( ngram.getTokCount() > 1 ) {
        cr.and("second").is(ngram.getSecond());
    }
    if( ngram.getTokCount() > 2 ) {
        cr.and("third").is(ngram.getThird());
    }
    final Query qry = new Query( cr );
    final Update updt = new Update().inc("count", ngram.getCount());
    template.upsert(qry, updt, NGram.class);
    return ngram;
}

[2]

Caused by: org.springframework.dao.DuplicateKeyException: E11000 duplicate key error index: sytrue.ngram.$_id_  dup key: { : "page two" }; nested exception is com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: sytrue.ngram.$_id_  dup key: { : "page two" }
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:52)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:1665)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:390)
at org.springframework.data.mongodb.core.MongoTemplate.doUpdate(MongoTemplate.java:920)
at org.springframework.data.mongodb.core.MongoTemplate.upsert(MongoTemplate.java:894)
at com.sytrue.ngram.repo.impl.NGramRepositoryImpl.save(NGramRepositoryImpl.java:43)
at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)

Upsert 永远不应该向我返回这个异常。我说的对吗?

【问题讨论】:

  • 有可能同时发生两个 upsert 吗?
  • 不,我正在通过队列对这些 upsert 进行序列化。

标签: spring mongodb upsert


【解决方案1】:

我只是猜测的问题可能如下:

您正在根据许多条件进行查找操作。这意味着如果由于参数(在标准中)的任何不匹配而失败,那么它将尝试插入文档。

所以,很有可能您正在尝试使用相同的 _id 更新同一个文档,但其他一些条件不匹配,导致它再次插入,这将导致重复键异常。考虑下面的例子

test:Mongo > db.example.update({ _id : 1, a : 1, b : 1},{ $set : {d : 1}}, true, false)
test:Mongo > db.example.find()
{ "_id" : 1, "a" : 1, "b" : 1, "d" : 1 }
test:Mongo > db.example.update({ _id : 1, a : 1, b : 2},{ $set : {d : 1}}, true, false)
E11000 duplicate key error index: test.example.$_id_  dup key: { : 1.0 }

【讨论】:

    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2020-01-15
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多