0

我正在使用游戏!框架 morphia-mongodb 模块,我看到它有很好的内置插件来进行组聚合。不幸的是,所有示例仅显示按固定字段进行分组/聚合,而我需要按计算字段进行聚合:按天分组的时间戳。我想知道是否有人知道正确的方法?

我知道我可以求助于原生地图/减少(它本身需要一点挖掘才能弄清楚,所以我在这里发布以供参考,使用电影和放映时间):

        DBCollection coll = Movie.col();
        String map = "function() { " +
            (this.showtime.getMonth() + 1) + '/' + this.showtime.getDate()}; "
            + "var key = {date: this.showtime.getFullYear() + '/' 
            + (this.showtime.getMonth() + 1)       
            + '/' + this.showtime.getDate()}; "
            + "emit(key, {count: 1}); }";

        String reduce = "function(key, values) { var sum = 0; "
            + " values.forEach( function(value) {sum += value['count'];} );"
            + " return {count: sum}; }";

        String output = "dailyShowingCount";

        MapReduceOutput out = coll.mapReduce(
            map, reduce, output, MapReduceCommand.OutputType.REPLACE, null);

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");    
        for (Iterator<DBObject> itr = out.results().iterator(); itr.hasNext();) {
            DBObject dbo = itr.next();

            String compoundKeyStr = dbo.get("_id").toString();
            String compoundValStr = dbo.get("value").toString();

            DBObject compKey = (DBObject)JSON.parse(compoundKeyStr);
            DBObject compVal = (DBObject)JSON.parse(compoundValStr);

            //don't know why count returns as a float, but it does, so i need to convert    
            Long dCount = new Double(
               Double.parseDouble(compVal.get("count").toString())
            ).longValue();

            Date date = df.parse(compKey.get("date").toString());
        }

但是,如果已经有一种优雅的内置方法可以使用 morphia 模块进行这种聚合,我想改用它。我的一个想法是在我的 java 类中创建一个虚拟字段(例如“getDay()”),然后通过它进行分组/聚合。这个事情谁有经验?

4

1 回答 1

0

最简单的方法是在模型中创建派生列并将其保存到数据库中。

@Entity Movie extends Model {
   public Date showTime;
   private Date showTimeDate;
   @OnUpdate
   @OnAdd
   void calcShowTimeDate() {
      Calendar c = Calendar.getInstance();
      c.setTime(showTime);
      c.set(Calendar.HOUR_OF_DAY, 0);
      c.set(Calendar.MILLISECOND, 0);
      c.set(Calendar.MINUTE, 0);
      c.set(Calendar.SECOND, 0);
      showTimeDate = c.getTime()
   }
}

然后您可以按照http://www.playframework.org/modules/morphia-1.2.4d/statisticsshowTimeDate上的说明在列上聚合

于 2012-01-23T20:31:13.260 回答