user3376856
user3376856

Reputation: 43

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

Upvotes: 3

Views: 4259

Answers (1)

Anand Jayabalan
Anand Jayabalan

Reputation: 12914

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}
    }}
])

Upvotes: 5

Related Questions