• MongoDB 批量插入或保存


    背景

    除了一般的MySQL中我们经常会用到批量插入或保存,此外,在大数据领域我们还常常还用到MongoDB,那么对于MongoDB怎么实现批量插入或保存呢?

    下面来直接看下代码

    代码

    实现了MongoDB批量插入或保存到数据库的功能,其中如果根据主键存在,就更新,不存在就插入

    Query query = new Query(new Criteria("recId").is(data.getRecId()));
    
    • 1
    @Override
    public void saveStaCharHisCurveHighwayData(List<StaCharHisCurveHighwayDto> staCharHisCurveHighwayDtoList) {
        log.info("StaCharHisCurveHighway正在写入mongodb数据库,数量 {} ", staCharHisCurveHighwayDtoList.size());
    
    	//更新或插入List
        List<Pair<Query, Update>> updateList = new ArrayList<>(staCharHisCurveHighwayDtoList.size());
    	
    	//bulk operation
        BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, StaCharHisCurveHighwayDto.class);
        
        //封装数据
        staCharHisCurveHighwayDtoList.forEach(data -> {
        	//recId为文档索引
            Query query = new Query(new Criteria("recId").is(data.getRecId()));
            Update update;
            Document doc = new Document();
            mongoTemplate.getConverter().write(data, doc);
            update = Update.fromDocument(new Document("$set", doc));
            Pair<Query, Update> updatePair = Pair.of(query, update);
            updateList.add(updatePair);
        });
    
    	//upsert = update + insert
        operations.upsert(updateList);
    	
    	//执行
        operations.execute();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    注意:执行的代码不能丢

    operations.execute();
    
    • 1
  • 相关阅读:
    游程编码(Run Length Coding)
    一文详解反转二叉树
    Bash中的变量引用:单引号和双引号的差异
    mysql中的悲观锁和乐观锁
    Qt事件传播机制 day8
    RabbitMQ 笔记
    Docker学习整理
    hadoop-eclipse-plugin-1.1.0
    Jumpserver堡垒机
    Postman如何做接口测试,那些不得不知道的技巧
  • 原文地址:https://blog.csdn.net/weixin_41405524/article/details/125626455