我正在使用游戏!框架 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()”),然后通过它进行分组/聚合。这个事情谁有经验?