MongoDB Aggregate -如何使用前一阶段的值作为下一阶段的字段名?

w7t8yxp5  于 2022-12-22  发布在  Go
关注(0)|答案(1)|浏览(111)

我有一个聚合查询,如下所示:

...
{
    '$unwind': {
      path: '$modifier'
    }
  }, {
    '$group': {
      '_id': {
        'date': {
          '$dateToString': {
            'format': '%d/%m/%Y', 
            'date': '$updatedTime'
          }
        }
      }, 
      '$$modifier': { '$sum': 1 }
    }
  },
...

我想把上一阶段的结果modifier值($unwind)作为下一阶段的字段($group),具体如下图所示,我该如何实现?
MongoDB aggregation question detailed picture

  • -当前--
    这是$unwind级的输出:
    x一个一个一个一个x一个一个二个x
    这是$group级的输出:
_id: { date:"27/03/2020" }
modifier:1
  • -预期--
    $unwind级的输出:
updatedTime:2020-03-27T11:02:43.608+00:00
modifier:"james@email.com"
updatedTime:2020-03-27T11:02:43.608+00:00
modifier:"eric@email.com"

这是$group级的输出:

_id: { date:"27/03/2022" }
james@email.com:1
eric@email.com:1
total:2

Notice that "james@email.com" and "eric@email.com" come from $unwind stage which is before $group stage. total is the total of modifier (examples: 'james@email.com' and 'eric@email.com') values. Any suggestion is appreciated.

afdcj2ne

afdcj2ne1#

它不是直接的,但是你需要同时用属性date和email分组,然后再用date分组,构造修饰符数组,然后在根目录中替换它,

  • $group乘以updatedTimemodifier,得到总数
  • $group,构造键值对中modifiercount的对象数组
  • $arrayToObject将键值对转换为对象
  • $mergeObject来合并所需的属性,就像我们将date属性和上面的数组添加到对象操作结果一样
  • $replaceRoot以替换文档根中的上述合并对象
{
    "$group": {
      "_id": {
        "date": {
          "$dateToString": {
            "format": "%d/%m/%Y",
            "date": "$updatedTime"
          }
        },
        "modifier": "$modifier"
      },
      "count": { "$sum": 1 }
    }
  },
  {
    "$group": {
      "_id": "$_id.date",
      "modifiers": {
        "$push": {
          "k": "$_id.modifier",
          "v": "$count"
        }
      },
      "total": { "$sum": "$count" }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          { 
            "date": "$_id",
            "total": "$total"
          },
          { "$arrayToObject": "$modifiers" }
        ]
      }
    }
  }

相关问题