MongoDB: Group by Date

MongoDB’s Group by Date feature allows users to group documents in a collection by date. This is a useful tool in data analysis since it allows users to quickly identify patterns or trends in data based on the date it was collected. It’s also useful for discovering correlations between different data points or parameters. Group by Date is especially useful when analyzing large datasets since it enables users to quickly and easily identify trends and patterns in the data.


You can use the following syntax to group documents by date in MongoDB:

db.collection.aggregate([
  {$group:{ _id:{$dateToString:{format: "%Y-%m-%d", date: "$day"}}, count:{ $sum: 1}}}
])

Note that day is the name of the date field that we’d like to group by in this example.

The following examples show how to use this syntax with a collection sales with the following documents:

db.sales.insertOne({day: new Date("2020-01-20"), amount: 40})
db.sales.insertOne({day: new Date("2020-01-21"), amount: 32})
db.sales.insertOne({day: new Date("2020-01-22"), amount: 19})
db.sales.insertOne({day: new Date("2020-01-23"), amount: 29})
db.sales.insertOne({day: new Date("2020-01-24"), amount: 35})

Example 1: Group by Date & Count

We can use the following code to count the number of documents, grouped by date:

db.sales.aggregate([
  {$group:{ _id:{$dateToString:{format: "%Y-%m-%d", date: "$day"}}, count:{ $sum: 1}}}
]) 

This query returns the following results:

{ _id: '2020-01-20', count: 2 }
{ _id: '2020-01-22', count: 1 }
{ _id: '2020-01-21', count: 2 } 

From the results we can see:

  •  The date 2020-01-20 occurs 2 times.
  •  The date 2020-01-22 occurs 1 time.
  •  The date 2020-01-21 occurs 2 times.

Example 2: Group by Date & Count (Then Sort)

We can use the following code to count the number of documents, grouped by date, and sort the results based on count ascending:

db.sales.aggregate([
  {$group:{_id:{$dateToString:{format: "%Y-%m-%d", date: "$day"}}, count:{ $sum: 1}}},
  {$sort: {count:1}} 
]) 

This query returns the following results:

{ _id: '2020-01-22', count: 1 }
{ _id: '2020-01-20', count: 2 }
{ _id: '2020-01-21', count: 2 } 

db.sales.aggregate([
  {$group:{_id:{$dateToString:{format: "%Y-%m-%d", date: "$day"}}, count:{ $sum: 1}}},
  {$sort: {count:-1}} 
]) 

This query returns the following results:

{ _id: '2020-01-20', count: 2 }
{ _id: '2020-01-21', count: 2 }
{ _id: '2020-01-22', count: 1 } 

Note: You can find the complete documentation for the sort function .

The following tutorials explain how to perform other common operations in MongoDB:

x