一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2018-11-06 编辑:猪哥 来源:一聚教程网

前言

在项目开发中遇到了需要批量插入数据和更新数据的操作,但是在某度上搜并没有找到有用的东西,于是到stackoverflow中搜到如下解决方案:

 

实践

一、BulkOperations 批量插入

代码如下:

   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 批量更新

代码如下:

  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();

运行结果:

成功更新多条数据。

热门栏目