我在mongoDB中有一个集合。并且我在提交的“word”上创建了唯一索引。
我有以下添加收藏的方法:
private boolean add(String word, Map<String, Integer> docOccurrence, Map<String, Integer> totalOccurrence) {
db.requestStart();
BasicDBObject document = new BasicDBObject();
document.put(DB_COLLECTION_WORD_CAT_COL_WORD, SQLQueryValidation.validateBeforeWrite(word));
document.put(DB_COLLECTION_WORD_CAT_COL_DOC_OCCURRENCE, new BasicDBObject(docOccurrence));
document.put(DB_COLLECTION_WORD_CAT_COL_TOTAL_OCCURRENCE, new BasicDBObject(totalOccurrence));
try {
synchronized (LOCK_WRITE) {
table.save(document, WriteConcern.SAFE);
//System.out.println(wr.getField("ok"));
}
} catch (MongoException e) {
System.out.println("heh");
logger.error("Could not insert new row to word_cat : {}", e.getMessage());
return false;
}
return true;
}
但是,如果我输入一个肯定的词,就会出现此错误!
Could not insert new row to word_cat : insertDocument :: caused by :: 11000 E11000 duplicate key error index: cat.word_cat_english.$word_1 dup key: {"test_word" }
我希望它没有问题,因为使用.save而不是.insert
我已经使用过Cassandra,它具有自动upsert。
我该如何管理?
总而言之,mongoDB中错误处理的最佳方法是什么?
谢谢。
最佳答案
我在上面第二个回答“zsh”。换句话说,mongo怎么能猜到您是错误地尝试插入重复项,还是试图更新现有数据。
我会:
1)运行“按单词选择”,如果已经存在这样的文档,请保存其ID
2)使用mongo upsert:
http://docs.mongodb.org/manual/reference/method/db.collection.update/
只是警告一下,当我使用spring-data-mongo时,第二种方法更``低级''而较少``面向对象'',例如spring的实现不会调度事件,也不会执行乐观更新(尽管您可能要仔细检查一下,但我使用的是旧版本)。
关于mongodb - mongoDB中重复 key 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24244984/