How to Query in MongoDB and Group by Date


TL;DR: Here’s a quick example to query MongoDB documents created this year(2023) and group them by date, ie. how many my_doc were created today, yesterday, the day before yesterday, etc. The following statement works in a MongoDB client such as mongosh.

db.my_doc.aggregate([
    {
        $match: {
            created_at: { $gte: ISODate("2023-01-01")}
        }
    },
    {
        $group: {
            _id: {
                $dateToString: {
                    format: "%Y-%m-%d",
                    date: "$created_at"
                }
            },
            count: { $sum: 1 }
        }
    },
    {
        $sort: {_id: 1}
    }
])

Then here’s an equivalent example to do it with MongoEngine in Python:

def histogram(days=7):
  from_date = datetime.datetime.today() - datetime.timedelta(days=days)
  pipeline = [
    {
      "$match": { "created_at": { "$gte": from_date}}
    },
    {
      "$group": {
        "_id": { "$dateToString": { "format": "%Y-%m-%d", "date": "$created_at" }},
        "count": { "$sum": 1 }
      }
    },
    {
      "$sort": { "_id": 1 }
    }
  ]
  for row in MyDoc.objects.aggregate(pipeline):
    print(row)

Since I just started learning MongoDB, I guess this probably is not the most efficient way to do group-by in MongDB. I’ll see if there’s a better way.

,