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