前言
在項目開發中遇到了需要批量插入數據和更新數據的操作,但是在某度上搜并沒有找到有用的東西,于是到stackoverflow中搜到如下解決方案:
實踐
一、bulkoperations 批量插入
代碼如下:
1
2
3
4
5
6
7
8
9
10
|
testmodel m1 = new testmodel( "m1" , 10 ); testmodel m2 = new testmodel( "m2" , 20 ); // bulkmode.unordered:表示并行處理,遇到錯誤時能繼續執行不影響其他操作;bulkmode.ordered:表示順序執行,遇到錯誤時會停止所有執行 bulkoperations ops = mongotemplate.bulkops(bulkoperations.bulkmode.unordered, "test" ); ops.insert(m1); ops.insert(m2); // 執行操作 ops.execute(); |
運行結果:
成功插入多條數據。
二、bulkoperations 批量更新
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
update u1 = new update().set( "age" , 15 ); query q1 = new query(criteria.where( "name" ).is( "m1" )); update u2 = new update().set( "age" , 25 ); query q2 = new query(criteria.where( "name" ).is( "m2" )); bulkoperations ops = mongotemplate.bulkops(bulkoperations.bulkmode.unordered, "test" ); ops.updateone(q1,u1); ops.updateone(q2,u2); ops.execute(); |
運行結果:
成功更新多條數據。
最后,希望這些例子對網友們有幫助。也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/sinat_24044957/article/details/80646292