I have a shifts
collection like below
{
"_id" : ObjectId("5885a1108c2fc432d649647d"),
"from" : ISODate("2017-01-24T06:21:00.000Z"), //can be weekday, sat, sun
"to" : ISODate("2017-01-24T08:21:00.000Z"),
"jobId" : ObjectId("586d7d6acfc7e05669d6e2c8"),
"hourlyRate" : 32 //this wil vary based on **from** field
}
{
"_id" : ObjectId("5885a1108c2fc432d649647e"),
"from" : ISODate("2017-01-25T06:21:00.000Z"),
"to" : ISODate("2017-01-25T08:21:00.000Z"),
"jobId" : ObjectId("586d7d6acfc7e05669d6e2c8"),
"hourlyRate" : 32
}
{
"_id" : ObjectId("5885a1108c2fc432d649647f"),
"from" : ISODate("2017-01-26T06:21:00.000Z"),
"to" : ISODate("2017-01-26T08:21:00.000Z"),
"jobId" : ObjectId("586d7d6acfc7e05669d6e2c8"),
"hourlyRate" : 32
}
I want to be able to produce an output like this
Job A (This can be obtained using jobId)
- Weekday earnings - $50 (2 * $25)
- Saturday earnings - $90 (3 * $30)
- Sunday earnings - $100 (2 * $50) Total earnings = $240
Job B
- Weekday earnings..............
Total earnings = Job A + Job B ..... = $X
Weekday or Saturday or Sunday can be derived from from
field. For a Weekday, all days from Monday to Friday need to be grouped.
Number of hours can be derived by subtracting from
from to
.
So, I think the following needs to be done, but I am not able to implement in MongoDB
- Group by
jobId
, group by day extracted fromfrom
(also group all weekdays) and get the sum of hours extracted by subtractingfrom
andto
. - Finally, get the sum of all the above sums to get the total earnings
- Get the final sum of all job earnings.
I found a few similar questions but I am not able to apply it to my situation
mongodb group values by multiple fields
Mongodb Aggregation Framework | Group over multiple values?
How to group by multiple columns and multiple values in mongodb
USE CASE:
When a user visits a page called earnings, I need to show him the earnings for the last week for each job and total earnings (then he can change the date range). So, I intent the show the split up for each Job, further split by weekday, saturday and sunday earnings and total earnings and work hours for THAT job. And final total earnings which is a summation of all the individual job earnings.
P.S I am using MongoDB 3.4