首页 > 解决方案 > 如何通过 Spring Boot 获取 mongoDB 中的计数?

问题描述

我是 MongoDB 新手,所以如果我问一些愚蠢的问题,请合作。请参考下表

status:"Failure"
key:object
   accountID:"AKRRTTY"

谁能告诉我如何根据 acountID (这是键的子对象)找到状态计数?

状态可以是不同的类型:例如ProcessedBlocked

标签: javamongodbspring-boot

解决方案


您必须使用聚合来一次性获取所有状态的计数。

您将需要调整输出 pojo 以考虑聚合查询。理想情况下,您的 pojo 应该包含两个字段,一个用于状态 (_id),一个用于计数 (count)。

就像是

AggregationOperation match = Aggregation.match(Criteria.where("key.carrier").is(carrierId));
AggregationOperation group = Aggregation.group("status").count().as("count");
AggregationOperation project = Aggregation.project("count").andExclude("_id").andInclude(Fields.from(Fields.field("status", "_id")));


Aggregation agg = Aggregation.newAggregation(match,group,project);

List<YourPojo> results = mongoTemplate.aggregate(agg, colname, YourPojo.class).getMappedResult();

推荐阅读