我正在尝试获取过去15天内每天创建的记录数。我想出了下面的查询:
db.users.aggregate(
{ $group: {
_id: {$dayOfYear: '$created'},
created: {$sum:1},
date: {$first: '$created'}
}
},
{$sort: {_id: 1}},
{$limit: 15}
);
这几乎可行,但它也将从一年前开始计算几天。因此,如果在2/20/2014创建了2条记录,并且在2013年2月20日创建了3条记录,那么将返回5条计数(当我想要的只有2条时)。我希望也像下面这样分组:
db.users.aggregate(
{ $group: {
_id: {{$dayOfYear: '$created'},{$year: '$created'}},
created: {$sum:1},
date: {$first: '$created'}
}
},
{$sort: {_id: 1}},
{$limit: 15}
);
但这是一个语法错误。我应该如何计算在特定日期创建的记录?
答案 0 :(得分:2)
db.users.aggregate(
{ $group: {
_id: {
day: { $dayOfYear: '$created' },
year: { $year: '$created' }
},
count: { $sum: 1 },
date: { $first: '$created' }
}
},
{ $project: { _id: 0, date: 1, count: 1 } }, // Only for more clear result.
{ $sort: { date: -1 } }, // If you want to view last 15 days - sort by descending.
{ $limit: 15 }
);