spring - Mongodb upsert throwing DuplicateKeyException -
i error [2] time time when attempting upsert (increment or insert) document using method [1].
[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 com.mongodb.mongoexception$duplicatekey: e11000 duplicate key error index: sytrue.ngram.$_id_ dup key: { : "page two" } @ org.springframework.data.mongodb.core.mongoexceptiontranslator.translateexceptionifpossible(mongoexceptiontranslator.java:52) @ org.springframework.data.mongodb.core.mongotemplate.potentiallyconvertruntimeexception(mongotemplate.java:1665) @ org.springframework.data.mongodb.core.mongotemplate.execute(mongotemplate.java:390) @ org.springframework.data.mongodb.core.mongotemplate.doupdate(mongotemplate.java:920) @ org.springframework.data.mongodb.core.mongotemplate.upsert(mongotemplate.java:894) @ com.sytrue.ngram.repo.impl.ngramrepositoryimpl.save(ngramrepositoryimpl.java:43) @ sun.reflect.generatedmethodaccessor41.invoke(unknown source)
upsert should never return me exception. right?
the issue guessing might following :
you doing find operations based on many criteria. means if fails because of mismatch of param ( in criteria ) try insert document.
so, chances there, trying update same document same _id of other criteria not matching, causing insert again cause duplicate key exception. consider below example
test:mongo > db.example.update({ _id : 1, : 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, : 1, b : 2},{ $set : {d : 1}}, true, false) e11000 duplicate key error index: test.example.$_id_ dup key: { : 1.0 }
Comments
Post a Comment