Mongo:添加到汇总中时,$ match返回一个空数组

问题描述

我有这样的查询

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

工作正常,但我想将结果限制为当年,所以我添加了以下内容

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' },])
  .exec();

这总是返回一个空数组。 我不知道我在做什么错。

解决方法

您的inicioDeAniofinDeAnio变量只是字符串,如果要按日期查询,则需要使用 ISODate 。像这样:

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