简体   繁体   English

如何在mongodb中按周对文档进行分组

[英]How to group documents by week in mongodb

How do i calculate the total hours spend by each user on the basis of week and my week start from Friday to Thursday . 如何计算每个用户每周的总工作时间,而我的工作周从星期五到星期四

Records 记录

{
  "_id" : ObjectId("5a69cd076b2beec65fa900e9"),
  "clock_date" : ISODate("2018-01-13T00:00:00.000Z"),
  "clock_in_time" : "10:40:53",
  "clock_out_time" : "12:40:53", 
},
{
  "_id" : ObjectId("5a69cd076b2beec65fa900e9"),
  "clock_date" : ISODate("2018-01-12T00:00:00.000Z"),
  "clock_in_time" : "10:00:53",
  "clock_out_time" : "10:40:53", 
},
{
  "_id" : ObjectId("5a69cd076b2beec65fa900e9"),
  "clock_date" : ISODate("2018-01-20T00:00:00.000Z"),
  "clock_in_time" : "10:20:00",
  "clock_out_time" : "12:40:53", 
},
{
  "_id" : ObjectId("5a69cd076b2beec65fa900e9"),
  "clock_date" : ISODate("2018-01-21T00:00:00.000Z"),
  "clock_in_time" : "10:40:53",
  "clock_out_time" : "11:40:53", 
},

Result to be like 结果像

 {
  week:'Jan 05, 2018 to Jan 11, 2018'
  totalhourse : 4
 },
 {
  week:'Jan 12, 2018 to Jan 18, 2018'
  totalhourse : 2:23
 },

. . . . .

Summing up the total hours with this schema is going to be tough and we should have a lot of calculations, since you have captured the time in and time out as strings. 用这种模式总结总工作时间将很困难,并且我们应该进行大量计算,因为您已将时间输入和超时记录为字符串。 To find the difference we need to segregate hours:minutes:seconds and then we have to find the difference. 要找到差异,我们需要将hours:minutes:seconds分开,然后我们必须找到差异。

"clock_in_time" : "10:40:53",
"clock_out_time" : "12:40:53",

Alternatively you can modify your schema to capture the in time and out time as Date with time stamp. 或者,您可以修改架构以将输入和输出时间捕获为带时间戳的日期。

"clock_in_time" : ISODate("2018-01-13T10:40:53.123+05:30"),
"clock_out_time" : ISODate("2018-01-13T12:40:53.121+05:30"),

If this modification is done then you can use aggregation pipeline to get the desired result 如果完成此修改,则可以使用聚合管道来获得所需的结果

In aggregation pipeline first 首先在聚合管道中

  • Use $match and $and to filter the documents within the date range(here you can feed in week start date and week end date) 使用$ match和$ and过滤日期范围内的文档(您可以在其中输入周开始日期和周结束日期)

  • then use $subtract with $project 然后将$ subtract$ project一起使用

Please note this query will give you only one week's result at a time 请注意,此查询一次只会给您一周的结果

References: 参考文献:

Subtracting time 减去时间

$match with $and operator $与$ and运算符匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM