Using MongoDB to group by the difference in dates and retrieve the hour value

Currently, I am working on an application and I require some information from my database:

  • I have a model called "traitement" which includes a user,
  • The "traitement" model has a start date and an end date, both in Date format, allowing MongoDB to use ISODate()

What I am looking to achieve is to retrieve all the "traitements" by user for a specific date range, but in hours format. For instance, if a "traitement" started on 24/02/2015 08:00:00 and ended on 24/02/2015 at 10:00:00, I need to calculate and get "2" hours.

Below is my current code snippet:

@TraitementNettoyage.aggregate([
        {$group: {'_id': {user: '$user'}, time: {'$subtract': ['$dateSortie', '$dateEntre']}}},
        {$sort: {_id: 1}}
      ]).exec((err, res)=>
        console.log res
      )

This query is not functioning as it is indicating that $subtract is an unknown group operator.

EDIT : Although I can use $subtract, I am unsure how to group based on it. Can someone provide guidance?

Here's the revised code without grouping:

 Traitement.aggregate([
        {$project: {total: {$subtract: ['$dateSortie', '$dateEntre']}}},
        {$sort: {_id: 1}}
      ]).exec((err, res)=>
        console.log res
      )

The final step is to group it by the user attribute and I am struggling to make it work :-/

EDIT 2 :

Here is a sample document of the desired output:

[{
    "_id": {
        "user": {
            "_id": "5512a66db54f879c2887411f",
            "userLastname": "Toto",
            "userFirstname": "Toto"
        },
        "total": 17824
    }
},
{
    "_id": {
        "user": {
            "_id": "551408741ad3b66c19978e9a",
            "userLastname": "Foo",
            "userFirstname": "Foo"
        },
        "total": 939
    }
}]

And here is a simple "traitement" document :

    {"_id" : ObjectId("55153711eba735e4311f92a0"),
                    "dateEntre" : ISODate("2015-03-27T10:55:13.069Z"),
                    "dateSortie" : ISODate("2015-03-27T10:55:18.018Z"),
                    "user" : ObjectId("5512a66db54f879c2887411f"),
                    "__v" : 0
}

The ultimate goal is to calculate the SUM of all the durations (dateSortie-dateEntre) grouped by user.

Thank you in advance

Answer №1

After reviewing your inquiry (please provide a sample of documents with your schema), it appears that if your Traitement model has the structure outlined below:

/* 0 */
{
    "_id" : 1,
    "user" : "abc",
    "dateEntre" : ISODate("2014-03-01T08:00:00.000Z"),
    "dateSortie" : ISODate("2014-03-01T13:00:00.000Z")
}

/* 1 */
{
    "_id" : 2,
    "user" : "jkl",
    "dateEntre" : ISODate("2014-03-01T08:00:00.000Z"),
    "dateSortie" : ISODate("2014-03-01T10:30:00.000Z")
}
/* 2 */
{
    "_id" : 3,
    "user" : "jkl",
    "dateEntre" : ISODate("2014-03-01T12:00:00.000Z"),
    "dateSortie" : ISODate("2014-03-01T18:00:00.000Z")
}

Your aggregation framework should include a $project pipeline operation where you calculate the time difference between two dates using the $subtract operator, and then convert that difference into hours using the $divide operator. The final stage in the pipeline should involve the $group operator to group the documents and calculate the total hours:

Traitement.aggregate([ 
    { 
        $project: { 
            user: 1,             
            dateDifference: { 
                $divide: [{ 
                    $subtract: [ "$dateSortie", "$dateEntre" ]
                    }, 1000*60*60
                ] 
            }
         }
    },
    { 
        $group: { 
            _id: "$user",             
            total : { 
                $sum : "$dateDifference"
            }
        }
    } 
])

Results:

/* 0 */
{
    "result" : [ 
        {
            "_id" : "jkl",
            "total" : 8.5
        }, 
        {
            "_id" : "abc",
            "total" : 5
        }
    ],
    "ok" : 1
}

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

Setting up a new user in a mongoDB database using NodeJS

I'm currently working on setting up a new User in my mongo Database using Nodejs. I am aware that you can create a user through the command line interface with code like this: db.createUser({ user: 'USERNAME', pwd: passwordPrompt(), ro ...

What is the best way to retrieve information from an http website and display it in an html table using javascript

I am attempting to retrieve data from the specified site: . The website appears to feature a list of objects, and my goal is to extract each object enclosed in {} into separate columns within a row (6 columns total - one for gameNumber, one for teams, and ...

How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example: <div ng-repeat="outeritem in outerobject"> <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div> <d ...

Assign a unique ID to each Angular Material checkbox

Presently, I am facing an issue: I am required to generate md-checkboxes from a Database. The implementation is successful using ng-repeat. However, I am encountering difficulties in fetching the data from these checkboxes. Each entry in the Database has ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Using JavaScript to display a line using `document.write`

I'm having trouble displaying a line using the Document.Write function in JavaScript. When I submit the form, the line briefly appears and then disappears Any ideas on why this might be happening? <!DOCTYPE html> <html> <head& ...

Having difficulties importing Container from NextUi

Hey everyone, I'm relatively new to nodejs and I've run into an issue when trying to utilize components from NextUI. I followed the installation instructions from here, but I'm getting an error that says Module'@nextui-org/react' h ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

ngRepeat does not completely refresh the DOM when dealing with a basic array

I have a simple array of numbers shown below using ng-repeat: n = [1,2,3,4,5,6] The problem arises when I modify this array, for example: n=[1,2,3] Instead of fully reloading the DOM, only the last 3 div elements corresponding to array 4, 5, 6 are remo ...

Initiating rs.initiate() in MongoDB leads to high demands on disk space

Currently, I have two running mongod instances with the following parameters: --noprealloc --smallfiles --replSet mongors1 --dbpath /data/db --nojournal The main objective here is to establish a replicated environment with minimal disk usage for local de ...

Incorporating an AngularJs App into Joomla: A Step-by-

As someone who is currently learning both Angular and Joomla, I am curious about the possibility of integrating an Angular JS Application within Joomla. While Joomla is known for its ease in creating articles and managing content through the admin panel, i ...

Looking for a specific search term within the middle of strings in an array

Is there a way to improve the autocomplete feature of my input field so that it shows suggestions based on any part of the word typed in? I currently have it set up to only show suggestions if the input matches the start of a word in the array. How can I m ...

The issue of 'MessageChannel not defined' arises specifically on web pages that have implemented reCaptcha v2

I am currently working on scraping some websites that have implemented reCAPTCHA, but I keep encountering an error when loading the page's source: (node:15536) UnhandledPromiseRejectionWarning: ReferenceError: MessageChannel is not defined. Despite a ...

Choosing custom element children once they're connected to the DOM: A guide

My goal is to retrieve the value of transaction-name__inputbox when the user clicks on the transaction-add__button. The function transactionAddHandler is triggered upon clicking the button. However, my attempt to select this element using document.querySe ...

What is the most efficient method for converting a string into an object in a Node.js environment?

This code seems to be functioning correctly, but it appears quite lengthy. Is there a more concise approach to achieve the same result? The primary objective here is to extract a sorting parameter from an HTTP query and use it to sort a collection in Mong ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

The functionality of Jquery ceases to work once a setTimeout function is implemented

I need some help getting a series of functions to be delayed by 2 seconds using setTimeout. For some reason, whenever I try to implement this, the code stops executing altogether. I've double-checked the syntax and everything seems fine because it wor ...

What is the method for transforming an array object into an object?

How can I assign the values of an array object called hello to a constant called answer, changing the key value in the process? I've considered using Object.entries but couldn't quite get it right. Is there a way to achieve this? Here is my cod ...