【问题标题】:Mongoose Aggregation giving field name a name from valueMongoose 聚合从值中为字段名称命名
【发布时间】:2021-08-26 11:05:30
【问题描述】:

所以我目前正在尝试从集合中获取数据并按年份和类型对其进行分组,

      {
        $group: {
          _id: {
            year: { $dateToString: { format: "%Y", date: "$date" } },
            typeId: "$type",
          },
          count: { $sum: 1 },
        },
      },
      {
        $project: {
          _id: 0,
          "$_id.year": {
            $push: {
              _id: "$_id.typeId",
              typeCount: "$count",
            },
          },
        },
      },

无论如何,我在项目的字段名称中使用$ 时遇到错误,因为我想将结果作为键值数组排序:

years[year]: {
   count: num,
   typeId: String
}

提前致谢:D

【问题讨论】:

  • 我认为,您仍然需要使用第一次分组时的 year 值进行第二次分组。然后,您可以使用该结果来获得所需的输出。

标签: mongodb mongoose aggregation-framework


【解决方案1】:
  • $toString 将年份从数字类型转换为字符串类型,因为下面的操作需要它作为字符串类型
  • $arrayToObject将对象的键值数组转换为对象格式
  {
    $project: {
      _id: 0,
      years: {
        $arrayToObject: [
          [
            {
              k: { $toString: "$_id.year" },
              v: {
                typeId: "$_id.typeId",
                count: "$count"
              }
            }
          ]
        ]
      }
    }
  }

Playground

【讨论】:

  • 非常感谢您,我实际上是 Aggregation 的新手,这对我来说是新的,非常感谢!
猜你喜欢
  • 2015-05-18
  • 2021-05-15
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多