2013-05-15 125 views
0

我有以下模式:聚合框架MongoDB的

Customer ID 
Location Name 
Time of Visit 

以上商店在不同地点的所有用户的访问信息。

我想知道是否有办法在MongoDB中编写一个聚合查询,以便它可以通过一天中的不同部分提供总访问者信息,每个位置每天。

节这一天:

编辑:

12 am - 8 am 
8 am - 11 am 
11 am - 1 pm 
1 pm - 4 pm 
4 pm - 8 pm 
8 pm - 12 pm 

如果客户在同一天和当天不止一次相同部分访问的位置,应该只计算一次。但是,如果客户访问在同一天,但对于一天中的不同部分的位置,应该为每一个日子,他已经出现在该部分的计算恰好一次

例:

Customer 1 visits store A on day 1 at 9:30 AM 
Customer 1 visits store A on day 1 at 10:30 PM 
Customer 1 visits store B on day 2 at 9:30 AM 
Customer 1 visits store B on day 2 at 11:30 AM 
Customer 1 visits store B on day 2 at 2:45 PM 

Customer 2 visits store A on day 1 at 9:45 AM 
Customer 2 visits store B on day 1 at 11:00 AM 
Customer 2 visits store B on day 2 at 9:45 AM 

重复访问的最终输出:

Store B, Day 1, Section (00:00 - 08:00) : 0 Visitors 
Store B, Day 1, Section (08:00 - 16:00) : 2 Visitors 
Store B, Day 1, Section (16:00 - 24:00) : 1 Visitors 
Store B, Day 2, Section (00:00 - 08:00) : 0 Visitors 
Store B, Day 2, Section (08:00 - 16:00) : 2 Visitors 
Store B, Day 2, Section (16:00 - 24:00) : 0 Visitors 

有什么办法以上类型的查询可以使用聚合框架MongoDB的做什么?

回答

1

是的,这可以做得很简单。这与我在answer to your previous question中描述的查询非常相似,但不是按天汇总,而是需要按日间小时组合进行汇总。

首先,而不是做一个小组,您需要投影一个新的日期部分,您需要将您的“访问时间”字段转换为适当的小时表格。让我们来看看一个办法做到这一点:

{$project : { newDate: { 
        y:{$year:"$tov"}, m:{$month:"$tov"}, d:{$dayOfMonth:"$tov"}, 
        h: { $subtract : 
          [ { $hour : "$tov" }, 
          { $mod : [ { $hour : "$tov" }, 8 ] } 
          ] 
        } 
      }, 
      customerId:1, locationId:1 
      } 
} 

正如你可以看到这个产生的年,月,日,时,但小时被截断国防部8(所以你得到0,8(AM),或16又名下午4点。

接下来我们可以做的,我们之前也做了同样的步骤,但现在我们都聚集到不同级别的时间粒度。

有实现同样的事情的其他方式,你可以看到some examples of date manipulation上我的博客

+1

顺便说一句,{$ project}对于创建更好的格式也很有用e文件结果。例如,您可以使用{$ project:{Time:{$ cond:{$ eq:[“newDate.h”,0]},“Midnight-8:00am”等等类型的表达式将0,8 ,16成漂亮的范围。 :) –

+0

谢谢。 (a)12 AM - 8 AM(b)8 AM - 11 AM(c)11 AM - 1 PM(d)1 PM - 4 PM(e)4 PM - 8 PM和(f)8 PM - 12 PM? – Ouroboros

+1

你将不得不写一个类似于我在这里根据数字选择星期几字符串的{$ cond:}表达式的long和tedius表达式:http://www.kamsky.org/1/post/2013/ 03/more-fun-with-dates-and-aggregations.html即使是时间间隔,也可以更轻松地利用“$ mod”运算符。 –