代码之家  ›  专栏  ›  技术社区  ›  Sixthpoint

mongo时间间隔数据

  •  1
  • Sixthpoint  · 技术社区  · 6 年前

    {
       "_id":"5c59c35d8610f702d00e6f70",
       "stationId":"2",
       "listenerId":"807",
       "streamId":"37",
       "userAgentId":"7",
       "botDefinitionId":"18",
       "ipAddress":"50.116.14.48",
       "startTime":"2018-02-06T12:51:59.000Z",
       "endTime":"2018-02-06T12:53:56.000Z",
       "listenLength":"117",
       "totalDataUsed":"1433582",
    }
    

    使用springdatamongo,我想将这些数据分组到时间窗口中(比如说间隔15分钟)。我创建了以下工作查询:

    {
       '_id':{
          'year':{
             '$year':'$startTime'
          },
          'week':{
             '$week':'$startTime'
          },
          'dayOfMonth':{
             '$dayOfMonth':'$startTime'
          },
          'month':{
             '$month':'$startTime'
          },
          'hour':{
             '$hour':'$startTime'
          },
          'interval':{
             '$subtract':[
                {
                   '$minute':'$startTime'
                },
                {
                   '$mod':[
                      {
                         '$minute':'$startTime'
                      },
                      15
                   ]
                }
             ]
          }
       },
       'count':{
          '$sum':1
       }
    }
    

    _id:{
       year:2018   week:15   dayOfMonth:18   month:4   hour:18   interval:45
    },
    count:9
    

    如何使用 GroupOperation 在springdatamongo中指定form this聚合?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Areeb Ahmed    6 年前

    我能想到的一种方法是在$project stage中调用函数,而不是在$group stage中调用它们。

    提取出小时、分钟、年等字段 DateOperator 班级。 然后使用 SpEL andExpression 您的间隔字段为:

    andExpression("minute - minute % 15").as("interval")
    

    这将用小时、间隔、年等字段重塑文档,然后按间隔和所需的其他字段对它们进行分组。

    Aggregation agg = Aggregation.newAggregation(
    
        Aggregation.project()
            .and(DateOperators.Minute.minute("$timestamp")).as("minute")
            .and(DateOperators.Hour.hour("$timestamp")).as("hour")
            .and(DateOperators.DayOfMonth.dayOfMonth("$timestamp")).as("dayOfMonth"),
    
        Aggregation.project("hour","dayOfMonth","minute")
            .andExpression("minute - minute % 15").as("interval"),
    
        Aggregation.group("hour","dayOfMonth","interval")
            .addToSet("hour").as("hour")
            .addToSet("dayOfMonth").as("dayOfMonth")
            .addToSet("interval").as("interval")
            .count().as("count")
    );
    
    List<QueryResult> result = mongoTemplate.aggregate(agg, "collection_name", QueryResult.class).getMappedResults();