You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pymongo多键分组按FragCount排序拼接Values数组的实现方案

实现方案

你可以直接使用MongoDB聚合管道完成需求,完整查询语句如下:

db.collection.aggregate([
  // 可选:如果需要筛选指定的MeasurementId和SensorNodeId,取消注释下面的match阶段
  // {
  //   $match: {
  //     MeasurementId: 110,
  //     SensorNodeId: "29a24a99"
  //   }
  // },
  // 先按FragCount升序排序,保证后续数组拼接顺序正确
  {
    $sort: { FragCount: 1 }
  },
  // 第一层分组:按唯一标识+ValueMapping分组,拼接同类型的Values数组
  {
    $group: {
      _id: {
        MeasurementId: "$MeasurementId",
        SensorNodeId: "$SensorNodeId",
        GatewayId: "$GatewayId",
        ValueMapping: "$ValueMapping"
      },
      concatValues: { $push: "$Values" }
    }
  },
  // 把二维数组合并为一维拼接数组
  {
    $addFields: {
      concatValues: {
        $reduce: {
          input: "$concatValues",
          initialValue: [],
          in: { $concatArrays: ["$$value", "$$this"] }
        }
      }
    }
  },
  // 第二层分组:按MeasurementId+SensorNodeId分组,组装ValueMapping为键的键值对
  {
    $group: {
      _id: {
        MeasurementId: "$_id.MeasurementId",
        SensorNodeId: "$_id.SensorNodeId",
        GatewayId: "$_id.GatewayId"
      },
      mappingPairs: {
        $push: {
          k: { $toString: "$_id.ValueMapping" },
          v: "$concatValues"
        }
      }
    }
  },
  // 转换为要求的输出结构
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            MeasurementID: "$_id.MeasurementId",
            SensorNodeID: "$_id.SensorNodeId",
            GatewayID: "$_id.GatewayId"
          },
          { $arrayToObject: "$mappingPairs" }
        ]
      }
    }
  }
])

逻辑说明

  • 排序阶段提前对FragCount升序处理,保证同一个ValueMapping下的Values数组严格按碎片顺序拼接
  • 两层分组逻辑分别处理「同类型Value数组拼接」和「按业务主键聚合输出」两个核心需求
  • 最终输出结构完全匹配你要求的格式,ValueMapping的值会直接作为对象的键,对应拼接完成的Values数组

内容的提问来源于stack exchange,提问作者usama aslam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:15:05