首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SpringData - Mongo聚合

SpringData - Mongo聚合
EN

Stack Overflow用户
提问于 2015-11-13 00:05:51
回答 1查看 493关注 0票数 3

我与MongoDB和Spring的聚合框架进行了相当长时间的斗争,实际上我想知道我想要做的事情是否真的是可能的。

我有下列蒙古文件:

代码语言:javascript
复制
{
  "_id": ObjectId("564520fad4c64dd36fb1f0a4"),
  "_class": "com.sample.Purchase",
  "created": new Date(1447371002645),
  "productId": NumberLong(12),
  "clientId": "c1",
  "price": NumberLong(20)
}

我想创建以下统计数据:

代码语言:javascript
复制
List<ClientStatsEntry> entries;

public class ClientStatsEntry  {
   private String clientId;
   private Date firstSeen;
   private Date lastSeen;
   private Long totalPriceSpend;
   private long totalCount;
}

因此,基本步骤是:

  1. 由productId收集的过滤器(匹配)
  2. 用clientIds (groupBy)拆分所有剩余的元素
  3. 检索第一项和最后一项的创建日期。
  4. 汇总所有价格并在"totalPrice“中存储
  5. 清点所有购买的物品并将其储存在"totalCount“中

我试着从这个方法开始,但是我找不到如何在一个聚合样条中完成所有事情:

代码语言:javascript
复制
Aggregation agg = newAggregation(
            match(Criteria.where("productId").is(productId)),
            group("clientId").sum("price").as("totalPriceSpend"),
            Aggregation.project("totalPriceSpend", "productId").and("productId").previousOperation());
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-13 09:05:44

我相信您正在寻找这个聚合管道(注释表示概述的步骤):

代码语言:javascript
复制
db.purchase.aggregate([
    /* 1. Filter collection by productId (match) */
    {
        "$match": {
            "productId": productId
        }
    },
    /* 2. Split all remaining elements by clientIds (groupBy) */
    {
        "$group": {
            "_id": "$clientId",
            "firstSeen": { "$min": "$createdDate"}, // 3. a) Retrieve the created date of the first entry
            "lastSeen": { "$max": "$createdDate"}, // 3. b) Retrieve the created date of the last entry
            /* 4. Sum up all prices and store in "totalPrice" */
            "totalPriceSpend": {
                "$sum": "$price"
            },
            /* 5. Count all purchases and store it in "totalCount" */
            "totalCount": {
                "$sum": 1
            }
        }
    }
])

Spring数据MongoDB聚合等效如下:

代码语言:javascript
复制
Aggregation agg = Aggregation.newAggregation( 
    match(Criteria.where("productId").is(productId)),
    group("clientId")
        .min("createdDate").as("firstSeen")
        .max("createdDate").as("lastSeen")
        .sum("price").as("totalPriceSpend")
        .count().as("totalCount"),
    project("firstSeen", "lastSeen", "totalPriceSpend", "totalCount")
        .and("clientId").previousOperation()
); 
AggregationResults<ClientStatsEntry> result = 
    mongoTemplate.aggregate(agg, ClientStatsEntry.class);
List<ClientStatsEntry> clientStatsList = result.getMappedResults();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33683746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档