【问题标题】:Reusing/splitting $match results in a mongo aggregation重用/拆分 $match 会导致 mongo 聚合
【发布时间】:2019-08-01 23:26:36
【问题描述】:

我有一个 mongo 集合,用于存储有关页面视图的数据,例如位置、用户类型(例如管理员、用户)和在页面上花费的时间。我想使用$match 获取文档的子集,然后使用$group 按状态和用户类型对它们进行分组。 $match 相当昂贵,所以我想知道是否有办法通过聚合管道以某种方式重用 $match 并获得两组分组数据,而不是需要运行两个聚合。

当前的js伪代码:

groupedByState = Views.aggregate([
  $match: { ... },
  $group: {
    _id: '$state',
    secondsViewed: { $avg: '$seconds_viewed' },
  },
])

groupedByUserType = Views.aggregate([
  $match: { ... },
  $group: {
    _id: '$user_type',
    secondsViewed: { $avg: '$seconds_viewed' },
  },
])

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用$facet 聚合运算符对$match 的输出执行多个$group 操作:

    Views.aggregate([
      $match: { ... },
      $facet: {
        byState: [{
          $group: {
            _id: '$state',
            secondsViewed: { $avg: '$seconds_viewed' }
          }
        }],
        byUserType: [
          $group: {
            _id: '$user_type',
            secondsViewed: { $avg: '$seconds_viewed' }
          }
        }]
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多