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

 平凡的稳健投资 发布于 2022-10-27 23:40

我想用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 batchToSave, String collectionName);

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

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 );
        }

    如果你有更好的解决方案,欢迎交流。

    2022-10-29 05:30 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有