title: Mongodb upsert throwing DuplicateKeyException
body: <p>I do get this error [2] from time to time when attempting to upsert (increment or insert) a document using method [1].</p>
  
  <p>[1]</p>
  
  <pre><code>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() &gt; 1 ) {
          cr.and("second").is(ngram.getSecond());
      }
      if( ngram.getTokCount() &gt; 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;
  }
  </code></pre>
  
  <p>[2]</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Upsert should never return me this exception. Am I right?</p>