开发者社区> 问答> 正文

用spring-data-mongodb批量插入数据,如何知道有一部分数据没有插入成功?

我想用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);
然而这里存在一个问题:当有重复的唯一索引时,插入操作会“部分成功”——某些文档插入成功,某些插入失败。我想知道什么时候发生的插入失败,哪些失败了,哪些成功了。然而,上面的接口没有返回值。有谁碰到过这个问题吗?

展开
收起
蛮大人123 2016-06-15 11:33:38 5989 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    见相同的问题,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 );
        }
    2019-07-17 19:39:00
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Data as a Service - 数据即服务 -- MongoDB⾼级应⽤模式 立即下载
阿里云MongoDB云服务构建 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载