Group by dates in a MongoDB collection?


To group by dates, use $group in MongoDB aggregate. Let us create a collection with documents −

> db.demo657.insertOne({
...       id: 1,
...       Name: "Chris",
...       DueDate: new ISODate("2020-04-22")
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea064b44deddd72997713d6")
}
> db.demo657.insertOne(
... {
...    id: 1,
...    Name: "John",
...    DueDate: new ISODate("2020-04-22")
... }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea064b44deddd72997713d7")
}
> db.demo657.insertOne(
... {
...    id: 1,
...    Name: "Chris",
...    DueDate: new ISODate("2020-04-22")
... }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea064b44deddd72997713d8")
}

Display all documents from a collection with the help of find() method −

> db.demo657.find();

This will produce the following output −

{ "_id" : ObjectId("5ea064b44deddd72997713d6"), "id" : 1, "Name" : "Chris", "DueDate" : ISODate("2020-04-22T00:00:00Z") }
{ "_id" : ObjectId("5ea064b44deddd72997713d7"), "id" : 1, "Name" : "John", "DueDate" : ISODate("2020-04-22T00:00:00Z") }
{ "_id" : ObjectId("5ea064b44deddd72997713d8"), "id" : 1, "Name" : "Chris", "DueDate" : ISODate("2020-04-22T00:00:00Z") }

Following is the query to group by dates in MongoDB collection −

> db.demo657.aggregate([
...    {$match: {id:1, DueDate: {$gte:new ISODate('2020-04-21'), $lt:new ISODate   ("2020-04-23")}}},
...    {$project:
...    {day: {'$dayOfMonth': '$DueDate'},month: {'$month':'$DueDate'},year: {'$year':'$DueDate'},Name:"$Name" }
... },
...    {$group: {
...       _id: {day:'$day',month:'$month',year:'$year'},
...       ListOfNames: {$push:{Name:'$Name'}}
...    }}
... ])

This will produce the following output −

{ "_id" : { "day" : 22, "month" : 4, "year" : 2020 }, "ListOfNames" : [ { "Name" : "Chris" }, { "Name" : "John" }, { "Name" : "Chris" } ] }

Updated on: 13-May-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements