MongoDB返回过去一个月中每天的文档数 [英] MongoDB Return the count of documents for each day for the last one month
本文介绍了MongoDB返回过去一个月中每天的文档数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个每天更新文件的集合。有人可以提供一些建议,以便返回过去一个月每天添加的文件数。
我有一个带有创建时间戳的字段,如下所示..
createdTimestamp:ISODate(2014-03-19T19:25:23.351Z)
I have a collection with documents updating everyday. Can someone provide me some suggestion for returning the count of the documents added on every day for the last one month. I am having a field with created time stamp as shown here .. "createdTimestamp" : ISODate("2014-03-19T19:25:23.351Z")
推荐答案
您可以使用聚合框架实现你想要的:
You could use the aggregation framework to achieve what you want:
db.collection.aggregate([
// Get only records created in the last 30 days
{$match:{
"createdTimestamp":{$gt: new Date(ISODate().getTime() - 1000*60*60*24*30)}
}},
// Get the year, month and day from the createdTimeStamp
{$project:{
"year":{$year:"$createdTimestamp"},
"month":{$month:"$createdTimestamp"},
"day": {$dayOfMonth:"$createdTimestamp"}
}},
// Group by year, month and day and get the count
{$group:{
_id:{year:"$year", month:"$month", day:"$day"},
"count":{$sum:1}
}}
])
这篇关于MongoDB返回过去一个月中每天的文档数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文