0
我正在使用Play! framework morphia-mongodb模塊,我發現它具有很好的內置功能,可以進行組合。不幸的是,所有示例僅顯示按固定字段進行分組/彙總,而我需要按計算字段進行彙總:按日期分組的時間戳。我想知道是否有人知道正確的方法?玩!框架嗎啡模塊組按日期桶聚合
我知道我可以再打一個本地的map/reduce(這本身花了小挖搞清楚,所以我在這裏發帖參考,使用電影和放映時間):
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());
}
但如果已經有一個優雅的內置方式來與嗎啡模塊進行聚合,我想用它來代替。我想過的一個想法是在我的java類中創建一個虛擬字段(例如「getDay()」),然後通過它進行分組/聚合。有人對此有經驗嗎?