Spring Data Mongodb 批量操作示例 [英] Spring Data Mongodb Bulk Operation Example

查看:66
本文介绍了Spring Data Mongodb 批量操作示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我一个完整的Spring Data Mongodb DB批量操作示例.

Can some one please point me a complete example of Spring Data Mongodb DB bulk operation example.

我正在尝试使用 spring 数据 mongodb 切换到批量更新.找不到一个很好的例子.

I am trying to switch to bulk updates using spring data mongodb. Not able to find a good example.

谢谢.

推荐答案

Spring 数据中的 BulkOprations mongodb 使用了 mongodb 中的 bulkWrite().
来自 mongoDB 文档 ->

BulkOprations in Spring data mongodb uses bulkWrite() from mongodb.
From mongoDB documentation ->

因此,当您想在一个查询中更新多个具有不同更新的实体时,您可以通过这个 bulkOps 来实现.

So When you want to update many entities with different updated in one query you can do that via this bulkOps.

让我们看一个例子,尽管它可能不是一个完美的例子.假设您有一个员工集合,其中包含在公司工作的员工.现在经过评估后,所有员工的工资都会发生变化,每个员工的工资变化都会有所不同,假设没有涉及百分比明智的加息,如果您想一次性更新变化,您可以使用bulkOps.

Let us see an example eventhough it may not be an perfect one. Lets consider you have an Employee Collection with employees working in a company. Now After appraisal there will be change in salary for all the employees, and each employee salary change will be different and let's pretend there is no percentage wise hike involved and if you want to update the changes in one go you can use bulkOps.

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.util.Pair;

public class Example {
    @Autowired
    MongoTemplate mongoTemplate;
    public int bulkUpdateEmployee(List<Pair<Query, Update>> updates){
        return mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED,"employees",Employee.class).updateMulti(updates).execute().getModifiedCount();
    }
}

--------------这里我们可以准备查询和更新对 --------------对于每个员工->---查询" - 员工的 id 是 blabla---"update"- 设置薪水为xxx

--------------Here we can prepare the pair of query and update from ------- -------for each employee-> ---"query" - id of employee is blabla ---"update"- set salary to xxx

这篇关于Spring Data Mongodb 批量操作示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆