3

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

friedo
  • 65,762
  • 16
  • 114
  • 184
user3376856
  • 43
  • 1
  • 5

1 Answers1

5

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}
    }}
])
Anand Jayabalan
  • 12,294
  • 5
  • 41
  • 52
  • Thanks Anand works great for me !!!! Is there a way that in my collection the createdTimeStamp is in GMT I need this in EST time stamps ... – user3376856 Mar 20 '14 at 17:32
  • No problem. StackOverflow's recommended practice is to post a new question since it's unrelated to this one. – Anand Jayabalan Mar 20 '14 at 18:33
  • 1
    Is it possible to get it like Date count 2014/03/20 5 2014/03/19 10 2014/03/15 15 Ryt now we are getting them in the array format which I can't view in table format ... – user3376856 Mar 20 '14 at 20:17
  • Look at [$concat](http://docs.mongodb.org/manual/reference/operator/aggregation/concat/), since you already have year, month & day. Like I said earlier, please post separate question on SO, as it might help other users too. – Anand Jayabalan Mar 20 '14 at 21:14