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