Group by day/month/week based on the date range in MongoDB


To group, use $week and $month in MongoDB. Let us create a collection with documents −

> db.demo133.insertOne({"Rank":18,"DueDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31980968e7f832db1a7f78")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-01-10")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31982568e7f832db1a7f79")
}
> db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-02-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31986568e7f832db1a7f7a")
}
> db.demo133.insertOne({"Rank":20,"DueDate":new ISODate("2020-02-01")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31986c68e7f832db1a7f7b")
}

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

> db.demo133.find();

This will produce the following output −

{ "_id" : ObjectId("5e31980968e7f832db1a7f78"), "Rank" : 18, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31982568e7f832db1a7f79"), "Rank" : 12, "DueDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e31986568e7f832db1a7f7a"), "Rank" : 12, "DueDate" : ISODate("2020-02-01T00:00:00Z") }
{ "_id" : ObjectId("5e31986c68e7f832db1a7f7b"), "Rank" : 20, "DueDate" : ISODate("2020-02-01T00:00:00Z") }

Following is the query to group by day/month/week based on the date range −

> db.demo133.aggregate([
...    {
...       "$project": {
...          "DueDateWeek": { "$week": "$DueDate" },
...          "DueDateMonth": { "$month": "$DueDate" },
...          "Rank": 1
...       }
...    },
... {
...    "$group": {
...       "_id": "$DueDateWeek",
...       "AvgValue": { "$avg": "$Rank" },
...       "MonthValue": { "$first": "$DueDateMonth" }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : 4, "AvgValue" : 16, "MonthValue" : 2 }
{ "_id" : 1, "AvgValue" : 15, "MonthValue" : 1 }

Updated on: 31-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements