MongoTemplate批量操作

(1)批量插入示例如下:
List insertDataList;
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
operations.insert(insertDataList);
BulkWriteResult result = operations.execute();
(2)批量修改示例如下:
List updateDataList;
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
updateDateList.forEach(date -> {
Query queryUpdate = new Query();
queryUpdate.addCriteria(where("_id").is(value));
Update update = new Update();
update.set(field1, value1).set(field2, value2);
operations.updateOne(queryUpdate, update);
});
BulkWriteResult result = operations.execute();
(3)利用BulkOperations的upsert方法可以同时支持插入和更新操作,示例如下:
List dataList = new ArrayList<>();
List<Pair<Query, Update>> updateList = new ArrayList<>(dataList.size());
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
dataList.forEach(data -> {
Query query = new Query(new
Criteria(field1).is(value1)).addCriteria(new Criteria(field2).is(value2));
Update update = new Update();
for (int index = 0; index < dataList.size(); index++) {
String key = data.getKey();
String value = data.getValue();
  update.set(key, value);
}
Pair<Query, Update> updatePair = Pair.of(query, update);
updateList.add(updatePair);
});
operations.upsert(updateList);
BulkWriteResult result = operations.execute();

备注:

  1. BulkOperations.BulkMode.UNORDERED 和
    BulkOperations.BulkMode.ORDERED的区别:
    UNORDERED是平行处理,即使某条记录出错了,其余的也会继续处理;
    ORDERED是队列排序处理,只要中途有个失败了,那么后续的操作流程就会终止了。 enum BulkMode {

    /** Perform bulk operations in sequence. The first error will
    cancel processing. */ ORDERED,

    /** Perform bulk operations in parallel. Processing will continue
    on errors. */ UNORDERED };

  2. BulkWriteResult更新结果集解释:
        getMatchedCount():选中更新或替换文档的数量,如果更新或者替换文档的值没有改变,getMatchedCount()的值比getModifiedCount()的值大;getModifiedCount()为修改文档的数量;getInsertedCount():使用insert()插入文档数;对于使用upsert()来更新和插入文档,插入文档的数量等于总更新和插入文档数减去getMatchedCount()的值;getDeletedCount():删除文档数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值