Alex
Alex

Reputation: 791

Mongo: $match returns an empty array when is added to aggregate

I have a query like this:

const data = await this.iveModel
      .aggregate([
        {
          $group: {
            _id: { $month: '$createdAt' },
            count: { $sum: 1 },
          },
        },
      ])
      .exec();

It works fine, but I want to limit the result to the current year, so I have added this:

const inicioDeAnio = moment()
      .startOf('year')
      .toISOString();

    const finDeAnio = moment()
      .endOf('year')
      .toISOString();

    const num = await this.iveModel
  .aggregate([
    {
      $match: {
        createdAt: {
            $gt: inicioDeAnio,
            $lt: finDeAnio
        }
    }
    },
    {
      $group: {
        _id: { $month: '$createdAt' },
        count: { $sum: 1 },
      },
    },
  ])
  .exec();

And this always returns an empty array. I do not know what I'm doing wrong.

Upvotes: 0

Views: 413

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

Your inicioDeAnio and finDeAnio variable is just string, if you want to query by date, you need to use ISODate. Something like:

...{
  $match: {
    createdAt: {
        $gt: ISODate(inicioDeAnio),
        $lt: ISODate(finDeAnio)
    }
}...

Upvotes: 1

Related Questions