0

Assuming I have the following document structure in my mongodb:

{
  _id: "tMSfNq9JR85XDaQe5"
  customerid: "QDGvBQhS6vYgZtnRr"
  employeeid: "QDGvBQhS6vYgZtnRr" 
  date: Sun Dec 07 2014 19:50:21 GMT+0800 (HKT) 
  projectid: "S83NEGHnrefvfASrf" 
  hours: 2
}

Is it possible to get total hours spent on a specific project and customer, grouped by employee and date, while querying data within specific date range, so that the output will be for example like:

{ "projectid":"XXX", "date":"Dec 1, 2014", "employeeid":"AAA", "totalHrs":"20" }
{ "projectid":"XXX", "date":"Dec 1, 2014", "employeeid":"BBB", "totalHrs":"11" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"AAA", "totalHrs":"3" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"BBB", "totalHrs":"5" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"CCC", "totalHrs":"18" }

Thanks

5
  • can you post your sample data?
    – Neo-coder
    Dec 9, 2014 at 11:16
  • @yogesh that's what inside the document structure posted above, this is a real copy of one of my documents data
    – MChan
    Dec 9, 2014 at 11:25
  • That does not look like an ISODate() so querying them will be complicated. Any chance you can change the type?
    – Martin
    Dec 9, 2014 at 11:27
  • @Martin yes I can change to ISODate. Thanks
    – MChan
    Dec 9, 2014 at 11:37
  • For this type of query it could be worth to have a look at the aggregation framework provided by MongoDB. Dec 9, 2014 at 11:40

2 Answers 2

1

Hi as per my understand I think you want to groups on projectid and employeeid as looking to your desired output so I think below aggregation may work in this case

db.collectionName.aggregate(
                       {"$group":{"_id":{"projectId":"$projectid","employeeId":"$employeeid","date":"$date"},
                       "totalHrs":{"$sum":"$hours"}}},
                      {"$project":{"projectid":"$_id.projectId",
                         "date":"$_id.date","employeeid":"$_id.employeeId",
                        "totalHrs":"$totalHrs",
                          "_id":0}}
                        )
2
  • You could further improve your answer, by formatting the date properly as in the expected output.
    – BatScream
    Dec 9, 2014 at 22:08
  • You may also want to use date operators in the group to collect results by day. Grouping just by date will separate documents from the same day with different times.
    – wdberkeley
    Dec 10, 2014 at 15:39
0

You need to group by projectid,date,employeeid

db.collectionname.aggregate({"$project":{"projectid":1,"date":1,"employeeid":1,"totalHrs":1}},
{"$group":{"_id":{"$projectId":"$projectid","date":"$date","employeeId":"$employeeid"}, 
"totalHrs":{"$sum":"$hours"}}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.