【问题标题】:Mongo: $match returns an empty array when is added to aggregateMongo:$match 添加到聚合时返回一个空数组
【发布时间】:2021-01-14 13:28:56
【问题描述】:

我有一个这样的查询:

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' },
        count: { $sum: 1 },
      },
    },
  ])
  .exec();

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

【问题讨论】:

    标签: mongodb mongoose nosql


    【解决方案1】:

    你的inicioDeAniofinDeAnio变量只是字符串,如果你想按日期查询,你需要使用ISODate。比如:

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

    【讨论】:

    • 我用新的日期做了它,它工作。非常感谢!
    猜你喜欢
    • 2021-10-24
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多