【问题标题】:Spring Boot MongoDB to get the sum of a field in a document returned by APISpring Boot MongoDB获取API返回的文档中字段的总和
【发布时间】:2023-03-29 02:10:02
【问题描述】:

我是 Spring Boot MongoDB 的新手。我正在开发一个每月费用的小型应用程序。

我想计算特定日期范围内文档返回的费用总额。

我能够获取给定日期范围内的文档。

如何单独捕获金额字段并将其汇总到获取的日期范围内?

控制器:

@GetMapping("/findBetDates/{stexpdate}/{edexpdate}")
List<mydataExp> getByExpdateBetw(@PathVariable String stexpdate, @PathVariable String edexpdate) {
    return expenseRepository.findExpDateBetw(stexpdate, edexpdate); 
}

存储库:

@Query("{'expdate' : { $gte: ?0, $lte: ?1 } }")   
List<mydataExp> findExpDateBetw(String stexpdate, String edexpdate);

型号:

@Document(collection = "mydataExp")
public class mydataExp {
    @Id
    private int id;
    private String expdate;
    private String exptype;
    private int expamt;
}

API 的 Postman 响应:

http://localhost:8080/findBetDates/12-01-2020/12-02-2020

[
    {
        "id": 121982,
        "expdate": "12-01-2020",
        "exptype": "Rent",
        "expamt": 1000
    },
    {
        "id": 121984,
        "expdate": "12-02-2020",
        "exptype": "Indian Stores",
        "expamt": 54
    }
]

【问题讨论】:

    标签: java mongodb spring-boot api rest


    【解决方案1】:

    我知道您需要使用投影并仅获取所有对象的expamt。您可以使用链接中提到的projection。我们将 1 用于我们想要检索的所有字段。 在您的情况下,查询将是

    @Query(value="{'expdate' : { $gte: ?0, $lte: ?1 } }", fields="{expamt : 1}")
    

    附:这是official documentation 子标题 6.3.2

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多