【问题标题】:Spring data mongo - Get sum of array of objectSpring data mongodb - 获取对象数组的总和
【发布时间】:2019-10-16 00:46:37
【问题描述】:

我有以下文件:

{
   pmv: {
        budgets: [
           {
              amount: 10
           },
           {   
              amount: 20
           }
         ]
     }
}

我需要对budgets 中每个对象的amount 字段求和。但也有可能budget 对象不存在,所以我需要检查一下。

我怎么能这样做?我见过很多问题,但对于预测,我只需要一个整数,在这种情况下为 30。

我该怎么做?

谢谢。

为 PUNIT 编辑 1

这是我尝试过的代码,但它给了我一个空数组

AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
            AggregationOperation unwind = unwind("pmv.budgets");
            AggregationOperation sum = group().sum("budgets").as("amount");

            Aggregation aggregation = newAggregation(filter, unwind, sum);

            mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            AggregationResults<String> aggregationa = mongoTemplate.aggregate(aggregation,"Iniciativas",String.class);

            List<String> results = aggregationa.getMappedResults();

【问题讨论】:

    标签: spring mongodb spring-boot aggregation


    【解决方案1】:

    您可以使用聚合管道来做到这一点

    db.COLLECTION_NAME.aggregate([
      {"pmv.budgets":{$exists:true,$not:{$size:0}}},
      {$unwind:"$pmv.budgets"},
      {amount:{$sum:"$pmv.budgets"}}
    ]);
    

    此管道包含三个查询:

    1. 获取具有非空和非空预算的文档
    2. $unwind 基本上是打开数组并为每个数组元素创建一个文档。例如如果一个预算文档有 3 个元素,那么它将创建 3 个文档并从每个数组元素填充预算属性。你可以阅读更多关于它here
    3. 使用$sum 运算符对所有budgets 属性求和

    你可以阅读更多关于聚合管道here

    编辑:根据 cmets,也为 java 添加代码。

    AggregationOperation filter = match(Criteria.where("pmv.budgets").exists(true).not().size(0));
    AggregationOperation unwind = unwind("pmv.budgets");
    AggregationOperation sum = group().sum("pmv.budgets").as("amount");
    
    Aggregation aggregation = newAggregation(filter, unwind, sum);
    
    mongoTemplate.aggregate(aggregation,COLLECTION_NAME,Output.class);
    

    你也可以用更内联的方式来做这件事,但我这样写是为了便于理解。

    我希望这能回答你的问题。

    【讨论】:

    • 我知道它在 Mongo 中的情况,但不知道如何将它翻译成 java
    • 嗨@Wrong,也添加了java代码。如果您需要更多帮助,请告诉我。
    • 我真的很抱歉@PunitTiwan,我忘了提到预算对象在另一个对象中。我已经用你的代码和我尝试过但成功的方法编辑了我的问题。
    • @Wrong 我认为您将不得不在sum 运算符中使用“pmv.budgets”而不是“budgets”,或者在unwind 中将预计名称命名为“budgets”
    • 我必须将“pmv”放在匹配条件中(它可能不存在,但如果 pmv 存在,预算总是存在),然后是 $budgets 在展开中,然后是“budgets”在总和中。我会接受你的回答,但请为未来的读者修改:)
    猜你喜欢
    • 2021-03-10
    • 2022-10-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2019-09-20
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多