Note that there are some explanatory texts on larger screens.

plurals
  1. POPlay! framework morphia module group aggregation by date bucket
    primarykey
    data
    text
    <p>I'm using the Play! framework morphia-mongodb module, and I see it has nice built-ins for doing group aggregation. Unfortunately all the examples only show grouping/aggregating by a fixed field, whereas I need to aggregate by a calculated field: timestamp grouped by day. I'm wondering if anyone knows the right approach to this?</p> <p>I know I can just resort to a native map/reduce (which itself took a little digging to figure out, so I'm posting here for reference, using Movies and showtimes):</p> <pre><code> 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&lt;DBObject&gt; 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()); } </code></pre> <p>But if there's already an elegant built-in way to do this aggregation with the morphia module, I'd like to use that instead. One thought I had was to create a virtual field in my java class (e.g. "getDay()") and then group/aggregate by that. Does anyone have experience with this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload