【问题标题】:Aggregation: Grouping based on array element in MongoDB聚合:MongoDB中基于数组元素的分组
【发布时间】:2022-08-23 21:04:18
【问题描述】:

我是 MongoDB 的新手,试图编写一个聚合函数,以便我的输入输出应与以下相同

[
  {
    \"_id\": {
      \"month\": 1,
      \"year\": 2022
    },
    \"childServices\": [
       {\"service\":\"MCT Latency\", \"sli\":99.9},
       {\"service\":\"MCT Packet Loss\", \"sli\":99.9}
      ],
    \"service\": \"Network\"
  },
  {
    \"_id\": {
      \"month\": 2,
      \"year\": 2022
    },
    \"childServices\": [
       {\"service\":\"MCT Latency\", \"sli\":98.9},
       {\"service\":\"MCT Packet Loss\", \"sli\":99.9}
      ]
    \"service\": \"Network\",
  }
]

在下面尝试过,但它没有按日期对每个 childService 进行分组。

[{
 $unwind: {
  path: \'$childServices\'
 }
}, {
 $group: {
  _id: {
   month: {
    $month: \'$date\'
   },
   year: {
    $year: \'$date\'
   }
  },
  service: {
   $first: \'$service\'
  },
  childServices: {
   $first: \'$childServices.service\'
  },
  sli: {
   $avg: \'$childServices.availability\'
  }
 }
}, {
 $sort: {
  \'_id.month\': 1,
  \'_id.year\': 1
 }
}]

样本数据

[{
  \"_id\": {
    \"$oid\": \"62fc99c00f5b1cb61d5f1072\"
  },
  \"service\": \"Network\",
  \"date\": \"01/02/2022 00:32:51\",
  \"childServices\": [
    {
      \"service\": \"MCT Latency\",
      \"availability\": 99.9,
    },
    {
      \"service\": \"MCT Packet Loss\",
      \"availability\": 99.9,
    }
},
{
  \"_id\": {
    \"$oid\": \"62fc99df0f5b1cb61d5f1073\"
  },
  \"service\": \"Network\",
  \"date\": \"02/02/2022 00:32:51\",
  \"childServices\": [
    {
      \"service\": \"MCT Latency\",
      \"availability\": 98.3,
   },
      \"service\": \"MCT Packet Loss\",
      \"availability\": 99.9,
   }
 }
]

基本上,我想进入 childService > 选择每个服务 > 按月+年对它们进行分组并获得他们的月平均值。

    标签: mongodb aggregation


    【解决方案1】:

    在分组之前,将日期从 string 转换为日期类型,如下所示:

    db.collection.aggregate([
      {
        $unwind: {
          path: "$childServices"
        }
      },
      {
        $addFields: {
          date: {
            "$toDate": "$date"
          }
        }
      },
      {
        $group: {
          _id: {
            month: {
              $month: "$date"
            },
            year: {
              $year: "$date"
            }
          },
          service: {
            $first: "$service"
          },
          childServices: {
            $first: "$childServices.service"
          },
          sli: {
            $avg: "$childServices.availability"
          }
        }
      },
      {
        $sort: {
          "_id.month": 1,
          "_id.year": 1
        }
      }
    ])
    

    游乐场link

    【讨论】:

    • 日期已经是日期类型。在 Playground 中,它不包括第二个 childService,即 MCT 丢包。每个月都应该有一个包含该月平均值的所有 childServices 的数组。用正确的预期输出更新了我的问题
    猜你喜欢
    • 2017-03-12
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2019-10-27
    • 2019-02-02
    相关资源
    最近更新 更多