除了一般的MySQL中我们经常会用到批量插入或保存,此外,在大数据领域我们还常常还用到MongoDB,那么对于MongoDB怎么实现批量插入或保存
呢?
下面来直接看下代码
实现了MongoDB批量插入或保存到数据库的功能,其中如果根据主键存在,就更新,不存在就插入
Query query = new Query(new Criteria("recId").is(data.getRecId()));
@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();
}
注意:
执行的代码不能丢
operations.execute();