前言
在項(xiàng)目開發(fā)中遇到了需要批量插入數(shù)據(jù)和更新數(shù)據(jù)的操作,但是在某度上搜并沒有找到有用的東西,于是到stackoverflow中搜到如下解決方案:
實(shí)踐
一、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:表示并行處理,遇到錯(cuò)誤時(shí)能繼續(xù)執(zhí)行不影響其他操作;bulkmode.ordered:表示順序執(zhí)行,遇到錯(cuò)誤時(shí)會停止所有執(zhí)行 bulkoperations ops = mongotemplate.bulkops(bulkoperations.bulkmode.unordered, "test" ); ops.insert(m1); ops.insert(m2); // 執(zhí)行操作 ops.execute(); |
運(yùn)行結(jié)果:
成功插入多條數(shù)據(jù)。
二、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(); |
運(yùn)行結(jié)果:
成功更新多條數(shù)據(jù)。
最后,希望這些例子對網(wǎng)友們有幫助。也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/sinat_24044957/article/details/80646292