Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Return the count of documents for each day for the last one month

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")

like image 617
user3376856 Avatar asked Feb 03 '26 18:02

user3376856


1 Answers

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}
    }}
])
like image 149
Anand Jayabalan Avatar answered Feb 05 '26 07:02

Anand Jayabalan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!