MongoDB:每天计数条目

时间:2016-04-25 16:56:22

标签: mongodb mongodb-query database

我正在尝试将我的SQL查询迁移到MongoDB。我每天都在计算数量。 我的MsSQL查询如下所示:

SELECT
datepart(DAY, Timestamp) as day,
datepart(MONTH, Timestamp) as month, 
datepart(YEAR, Timestamp) as year,
count(RowKey) as Counts               //uniq
FROM database
GROUP BY
datepart(YEAR, Timestamp),
datepart(MONTH, Timestamp), 
datepart(DAY, Timestamp) 
ORDER BY
datepart(YEAR, Timestamp),
datepart(MONTH, Timestamp), 
datepart(DAY, Timestamp) ASC

结果:

Old MsSQL Output

数据库结构扁平:

{
  ...
  Timestamp : 2016-01-17T17:46:10.984Z,
  RowKey: 123,
  ...
}
{
  ...
  Timestamp : 2016-01-05T12:49:12.675Z,
  RowKey: 124,
  ...
}
...

我是MongoDB的新用户,已经尝试了this,但它并没有按照我想要的方式运行。我会感谢提示。

1 个答案:

答案 0 :(得分:0)

这可以帮到你。

db.urcollection.aggregate(
  [

  {

 $project:

         {
           year: { $year: "$Timestamp" },
           month: { $month: "$Timestamp" },
           day: { $dayOfMonth: "$Timestamp" }
         }
     },
    {
    "$group":
     {
        "_id":{
        "year": "$year",
        "month": "$month",
        "day": "$day"
        } ,
        "YEAR": {
             "$first": "$year"
                 },
            "MONTH": {
             "$first": "$month"
            },
        "DAY": {
             "$first": "$day"
            }

     }
    },
   ]
)