日期范围内的Mongodb Sum字段和其他过滤器

时间:2014-12-09 11:12:26

标签: mongodb

假设我的mongodb中有以下文档结构:

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

在查询特定日期范围内的数据时,是否有可能在特定项目和客户上花费总时间(按员工和日期分组),以便输出例如:

{ "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" }

由于

2 个答案:

答案 0 :(得分:1)

嗨,根据我的理解,我认为你想在projectid和employeeid上分组,看看你想要的输出,所以我认为下面的聚合可能适用于这种情况

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

答案 1 :(得分:0)

您需要按照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"}}})