2

Is there a way to get the total number of documents in a MongoDB database by months (for example, so I can display a chart showing the evolution of the number of users) in a single request? or should I request each month individually?

I don't want to see the number of users created in a month but the total (this month + previous months).

user3491456
  • 327
  • 1
  • 3
  • 11
  • Use the [db.collection.count()](http://docs.mongodb.org/manual/reference/method/db.collection.count/) method e.g `db.users.count( { created_dt: { $gt: new Date('01/07/2014') } } )` – chridam Aug 18 '14 at 12:31
  • 1
    Do you have any field in the document that stores the creation date? Can you share a sample document from your collection? – Anand Jayabalan Aug 18 '14 at 12:33
  • 1
    Please give u example documents and show us what you have tried so far. – wdberkeley Aug 19 '14 at 16:15

1 Answers1

0

Each document in the collection has a field representing the date it was created. To get the total number of documents in a MongoDB database by months, use a range query to query for documents whose value for created_on is greater than a Date representing the start of the month, and less than a Date representing the end.

Assume the start date is 'start' and the end date is 'end'. Then the query will be,

db.users.count({created_on: {$gte: start, $lt: end}});

Here is a nice explanation relevant to this topic. http://cookbook.mongodb.org/patterns/date_range/

Refer the answers in this thread also. Find objects between two dates MongoDB

Community
  • 1
  • 1
Manorama
  • 69
  • 4