好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Data MongoDB 数据库批量操作的方法

前言

在项目开发中遇到了需要批量插入数据和更新数据的操作,但是在某度上搜并没有找到有用的东西,于是到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

查看更多关于Spring Data MongoDB 数据库批量操作的方法的详细内容...

  阅读:17次