Mongo 聚合操作

Mongo 聚合

mongo中的聚合通过不同的阶段对数据进行不同的操作,并将每一个阶段操作的结果传递到下一个阶段
mongo中常用的Satges

  • $match 对数据进行过滤, 用于条件筛选
  • project 投影,选择需要使用的字段、对数据进行操作等
  • group 分组,对数据进行分组统计
  • addFields 添加字段

其中的每一个Stage都可以重复出现,按出现的顺序执行操作。

mongo 聚合语句

[
    {"$match": {"operType": {"$in": ["1", "2", "3"]}}},
    {"$group": {"_id": {"secOrg": "$secOrg", "thrOrg": "$thrOrg", "userId": "$userId"}}},
    {"$addFields": {"type": "7", "secOrg": "$_id.secOrg", "thrOrg": "$_id.thrOrg", "userId": "$_id.userId"}},
    {"$group": {"_id": "$secOrg", "num": {"$sum": 1}}},
    {
      "$addFields": {
        "type": "7",
        "secOrg": "$_id.secOrg",
        "dataGroup": "$_id.secOrg"
      }
    }
  ]

match: 筛选特定类型的操作
group:对二级机构、三级机构、用户进行分组
addFields: 将二级结构、三级机构、用户id添加为字段
group:对二级机构分组,并统计数量
addFields:添加字段

使用 spring-data-mongo 进行聚合统计

Aggregation aggregation = Aggregation.newAggregation(
	Aggregation.match(Criteria.where("operType").in("1", "2", "3")),
	Aggregation.group("secOrg", "thrOrg", "userId"),
	Aggregation.addFields().addFieldWithValue("type", "7")
	.addField("secOrg").withValue("$_id.secOrg")
	.addField("thrOrg").withValue("$_id.thrOrg")
	.addField("userId").withValue("$_id.userId").build(),
	Aggregation.group("secOrg", "thrOrg").count().as("num"),
	Aggregation.addFields().addFieldWithValue("type", "7")
	.addField("fondsId").withValue("$_id.secOrg")
	.addField("dataGroup").withValue("$_id.thrOrg").build()

);
System.out.println(aggregation);
AggregationResults<StatisticLog> aggregate = mongoTemplate.aggregate(aggregation, "operationLog", Statistic.class);

如果需要对集合全部数据进行统计,即不分组,那么group中_id设置为null即可,而spring-data-mongo中使用无参的group()方法。

posted @   Dreamsrj  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示