MongoDB group by date intervals

前端 未结 2 1440
忘掉有多难
忘掉有多难 2020-12-16 08:15

I have a collection with datetime field and count filed:

{
    _id: null,
    datetime: new Date(),
    count: 1234
}
         


        
2条回答
  •  情深已故
    2020-12-16 08:28

    There are two different ways to do this. One is to issue a separate count() query for each of the ranges. This is pretty easy, and if the datetime field is indexed, it will be fast.

    The second way is to combine them all into one query using a similar method as your SQL example. To do this, you need to use the aggregate() method, creating a pipeline of $project to create the 0 or 1 values for the new "last_day", "last_week", and "last_month" fields, and then use the $group operator to do the sums.

提交回复
热议问题