-1

I've a model called Session. It has the id, device and Mongoose default time stamps. It's like this.

{
    _id: 5da977e431e58d4e7fc1da1c,
    device: 'Galaxy M10',
    createdAt: 2019-10-18T08:29:24.498Z,
    updatedAt: 2019-10-18T08:32:10.768Z,

  }

I want to group this sessions by the createdAt date. So I tried this.

const data = await db.Session.aggregate([
      { $match: { createdAt: { $gte: date } } },
      {
        $group: {
          _id: "$createdAt" ,
          count: { $sum: 1 }
        }
      }
    ]);

The result I got is this

{ _id: 2019-10-17T11:32:49.346Z, count: 1 },
  { _id: 2019-10-18T07:14:45.695Z, count: 1 },
  { _id: 2019-10-17T10:49:35.434Z, count: 1 },
  { _id: 2019-10-18T08:17:05.999Z, count: 1 },
  { _id: 2019-10-17T09:56:53.574Z, count: 1 },
  { _id: 2019-10-18T07:14:15.154Z, count: 1 },
  { _id: 2019-10-18T07:07:19.346Z, count: 1 },
  { _id: 2019-10-18T07:13:57.720Z, count: 1 },
  { _id: 2019-10-17T13:09:17.721Z, count: 1 },
  { _id: 2019-10-18T07:31:59.900Z, count: 1 },
  { _id: 2019-10-18T08:29:24.498Z, count: 1 },
  { _id: 2019-10-18T08:05:54.339Z, count: 1 }

My excepted result is

  { _id: 2019-10-18, count: 8 },
  { _id: 2019-10-17, count: 4 },

If this is on SQL instead of group by createdAt I do group by Date(createdAt). But how could I do this in MongoDB?

margherita pizza
  • 6,623
  • 23
  • 84
  • 152

1 Answers1

0

You can do this by extracting "dayOfMonth", "month" and "year" from the date and grouping by all three. The query will become:

db.Session.aggregate([
      { $match: { createdAt: { $gte: date } } },
      { $project: { dayOfMonth: { $dayOfMonth: $date },
                     month: { $month: $date },
                     year: { $year: $date },
     }
       },
      {
        $group: {
          _id: {    
               year: $year,
               month: $month,
               dayOfMonth: $dayOfMonth                
            } ,
          count: { $sum: 1 }
        }
      }
    ]);