Donato
Donato

Reputation: 2777

Return documents grouped by date in mongodb

In MySQL I would use an aggregate function to get records grouped by date:

SELECT COUNT(id), DATE(created_at) creation FROM records GROUP BY creation;

+-----------+------------+
| COUNT(id) | creation   |
+-----------+------------+
|        10 | 2015-04-22 |
+-----------+------------+
|        5  | 2015-11-22 |
+-----------+------------+

How could I achieve the same thing in MongoDB, given that I have an id and created_at column as well:

db.contacts.find()
{ "_id" : ObjectId("55394a8c6d616386e3020000"), "name" : "sfdsf fddfgfdg", "email" : "[email protected]", "fax" : "", "birth_date" : null, "phone" : "453454564", "phone_2" : "", "updated_at" : ISODate("2015-04-23T19:39:56.966Z"), "created_at" : ISODate("2015-04-23T19:39:56.966Z") }

Upvotes: 1

Views: 95

Answers (2)

mnemosyn
mnemosyn

Reputation: 46301

Aggregate using the $group aggregation command. To group by date rather than by datetime, you can use operators to extract year, month and day:

[
  {
    "$group" : {
       "_id" : { month: { $month: "$date" }, 
                 day: { $dayOfMonth: "$date" }, 
                 year: { $year: "$date" } },
       "count" : { $sum: 1 }
    }
  }
]

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

You could use the aggregation framework for this.

db.contacts.aggregate([
  {$group: {_id: "$created_at", count: {$sum: 1}}}
]);

Upvotes: 0

Related Questions