Experience the exciting features of the Play! framework Morphia module for grouping data by date buckets

I've been working with the Play! framework morphia-mongodb module and I'm impressed with its built-in group aggregation functionalities. However, all the examples I've come across demonstrate grouping/aggregating by a fixed field, whereas my requirement is to aggregate by a calculated field: timestamp grouped by day. Can anyone suggest the right approach for this?

Although resorting to a native map/reduce solution is an option (which took some effort to figure out initially, thus sharing it here for future reference using Movies and showtimes):

        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());
        }

However, if there's an elegant built-in method within the morphia module to achieve this type of aggregation, I'd prefer that route. One idea I had was creating a virtual field in my java class (e.g. "getDay()") and then perform grouping/aggregation based on that. Has anyone tried something similar before?

Answer №1

A simple method would be to generate a new column in your model and store it in the database.

@Entity Film extends Model {
   public Date screeningTime;
   private Date screeningTimeDate;
   @OnUpdate
   @OnAdd
   void calculateScreeningTimeDate() {
      Calendar cal = Calendar.getInstance();
      cal.setTime(screeningTime);
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MILLISECOND, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      screeningTimeDate = cal.getTime()
   }
}

After that, you can perform aggregation on the screeningTimeDate column by following the guidelines provided at

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Live Node.js and Next.js apps experiencing issues with functioning websockets

Within my nodejs backend at https://backend.example.com, the following code resides in my server.js file: const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 7500 }, () => { console.log('S ...

Learn the steps for incorporating a fresh item into a table from a pop-up interface with angularjs

I have been working on a simple customers table that includes information such as name, lastname, and age. I have successfully created a function that allows users to add a new customer, which is working fine. Additionally, I have implemented a pop-up wind ...

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

Passing the value of the selected calendar date to the controller

How can I pass the value generated by this calendar_date_select to the controller? Any suggestions on how to modify the onchange code? <%= calendar_date_select_tag "meeting_date_1", @time, :embedded => true, :time => true, :minut ...

Leveraging Vue.js as a development dependency in a TypeScript project

I am currently working on a .net core project where all client-side scripts are written in TypeScript. I have a desire to incorporate Vue.js into the TypeScript codebase. Below are snippets of the necessary configurations: tsconfig.json { "compilerOpti ...

I'm curious about this specific expression in express.js - can you explain its significance?

Could you please provide a thorough explanation of the following line of code in NodeJS: var app = module.exports = express.createServer(); ...

When incorporating Request.js and Cheerio.js into Node/Express, an unexpected outcome may occur where an empty

I am currently in the process of creating a basic web scraper using Request.js and Cheerio.js within Express. My main goal at the moment is to extract the titles of various websites. Instead of scraping each website individually, I have compiled them int ...

Discovering the technique to interact with obscured objects through a haze of PointsMaterial in three.js

Is there a property that allows objects behind a fog of multiple points to be clickable? I want to be able to click on objects even when they are obscured by the fog. Below is the code I am using to create and animate the fog: const loadFogEffect = () =&g ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

What is the best way to ensure that an element remains active even after a page refresh?

I have been using this code to activate the current element, which I came across on a website called "w3schools.com". However, whenever I refresh the page, the currently active element disappears. Is there a way to ensure that the active element remains hi ...

Exploring the colors of legend navigation icons in Google Pie charts

Is there a way to customize the color of the navigation links in Google pie charts (specifically the blue text in the bottom right corner)? https://i.sstatic.net/Hk591.png ...

Can you explain the purpose of the window.constructor and global.constructor functions in JavaScript?

Can someone explain the purpose of this function? I've been searching for information but can't find anything. I tested it in Firefox: window.constructor() // TypeError: Illegal constructor new window.constructor() // TypeError: Illegal constru ...

Wrap HTML attributes with double quotes using JavaScript

My goal is to add " around attributes that are missing them, using JavaScript. For example: <a class=external title=Title href="http://www.google.com" rel=external>My link</a> Should become: <a class="external" title="Title" href="http:/ ...

Leveraging mapReduce with Node.js and Mongoose

My goal is to find out how many students are in each locality. I have created a model that resembles the following structure: var mongoose = require('mongoose'); var schema = mongoose.Schema; var studentSchema = new mongoose.Schema( { "name":St ...

This issue with ng-include not functioning properly in Chrome but working fine in Firefox

My code is running only in Firefox and not working in Chrome. HTML Code <div ng-controller="myController1"> Select View: <select ng-model="employeeview"> <option value="1.html">1</option> < ...

What is the best way to display the HTML content being received from the database in the DOM?

I have received an object in this format [ { "BET": 57630343, "CUSTOMER": 181645, "SPORT": "MLB", "XX_FILL OPEN": "<button class=\"btn\" onclick=\"fillOpen(57630343)\">Fill Open</button>", "XX_VIEW": n ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Error: JSON unexpectedly encountered a '}' at position 102 in the syntax

I encountered an issue while trying to add new data to a MongoDB Atlas database using a simple Node/Express API. I am sending post requests through the REST client extension in VSCode but keep getting the aforementioned error. I am struggling to identify w ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

The challenge of removing an event listener

There are three Div elements with a box appearance. When the user clicks on any div, a copy of that div will be added to the end. The original clicked div will no longer be clickable, but the new div will be. This process can repeat indefinitely. I attemp ...