• MongoDB的批量查询条件进行批量更新数据


      今天遇到这样一个场景:在Java中批量更新MongoDB数据,不过每次更新的条件有不一样,那如何有效地进行更新操作呢?

           刚开始的时候,我是想到循环批量更新操作,即每一种查询条件进行一次批量更新过程,这样的思路就是多个查询条件就需要进行多次的批量更新,带来的弊端是跟数据库的连接交互太频繁了,消耗的时间都浪费在这些过程中了;那么今天我们可以通过另外一种方式来避免这种负面影响,只需要和数据库建立一次连接即可完成批量条件批量更新。

       (一)整体思路

      1、首先,将需要更新的数据存在一个List集合中

      2、然后,通过MongoTemplate的bulkOps方法返回的对象进行批量查询条件进行批量更新数据

      (二)逻辑代码

    MongoTemplate mongoTemplate = new MongoTemplate ();
    String collectionName = "testCollection";
    List<Object> updateEntityList = new ArrayList<>();
    List<Pair<Query, Update>> updateList = new ArrayList<>();
    BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
    updateEntityList .forEach(data -> {
                Query query = new Query(); // 需要根据具体的业务场景来添加查询条件
                Update update = new Update(); // 需要根据具体的业务场景通过newEntityList最新数据更新oldEntityList的某些数据
                update.set(key1, value1);
                update.set(key2, value2);
                update.set(key3, value3);
                Pair<Query, Update> updatePair = Pair.of(query, update);
                updateList.add(updatePair);
            });
    operations.updateMulti(updateList); 
    BulkWriteResult result = operations.execute();

      (三)小结

      这里主要用到了MongoDB的bulkOps方法,可以适用于不同的条件下批量操作。

    ------20200113勉

  • 相关阅读:
    @property
    UIViewController卸载过程(ios6.0以后)
    UIViewController卸载过程(ios6.0之前)
    UIViewController启动过程
    意淫原理,还是很有意思的
    协议
    多线程理解
    内存溢出与内存泄露
    jquery:实例方法
    计划,模型
  • 原文地址:https://www.cnblogs.com/bien94/p/12189890.html
Copyright © 2020-2023  润新知