我想用spring-data-mongodb的介面執行批次插入,每次插入100條資料。介面描述如下:
/**
* 参考:org.springframework.data.mongodb.core.MongoTemplate
* 参考:org.springframework.data.mongodb.core.MongoOperations
*
* Insert a list of objects into the specified collection in a single batch write to the database.
*
* @param batchToSave the list of objects to save.
* @param collectionName name of the collection to store the object in
*/
void insert(Collection<? extends Object> batchToSave, String collectionName);
然而這裡存在一個問題:當有重複的唯一索引時,插入操作會「部分成功」——某些文檔插入成功,某些插入失敗。 我想知道什麼時候發生的插入失敗,哪些失敗了,哪些成功了。然而,上面的介面沒有回傳值。有人碰到過這個問題嗎?
世界只因有你2017-05-02 09:19:54
遇見相同的問題,spring-data-mongodb
版本是1.8.2.RELEASE
.
在插入已有唯一索引id的資料時,沒有回傳值,也沒有異常,也不會影響原本的資料。
後面我的解決版本是在插入之前先查詢,如果根據id查詢到已經存在數據,則不執行插入,將該條數據保存到返回結果。
public Person getObject(String id) {
return mongoTemplate.findOne( new Query( Criteria.where( "id" ).is( id ) ),Person.class );
}
如果你有更好的解決方案,歡迎交流。