springboot使用MongoTemplate分组统计数据

根据messageStatus字段分组统计不同状态的数据量,相当于mysql里的group by 关键字。

springboot使用MongoTemplate分组统计数据_第1张图片

使用mongo里的aggregation聚合关键字。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author DAI
 * @date 2020/5/30 19:08
 * @Description TODO
 */
@Service
public class MessageReceiveLogDaoImpl implements MessageReceiveLogDao {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public List countByMessageStatus() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.group("messageStatus").count().as("count"),
                Aggregation.project("count").and("messageStatus").previousOperation()
        );
        AggregationResults outputTypeCount = mongoTemplate.aggregate(aggregation, MessageReceiveLog.class, MessageCount.class);
        return outputTypeCount.getMappedResults();
    }
}

结果集类

import lombok.Data;

/**
 * @author DAI
 * @date 2020/6/1 11:56
 * @Description 分组求和
 */
@Data
public class MessageCount {

    String messageStatus;

    Long count;
}

前端返回结果

springboot使用MongoTemplate分组统计数据_第2张图片

你可能感兴趣的:(mongo,springboot,mongodb,spring,boot)