MongoDB - 查询计算并对多项进行分组

MongoDB - Query calculation and group multiple items

假设我有以下数据:

{"Plane":"5546","Time":"55.0", City:"LA"}
{"Plane":"5548","Time":"25.0", City:"CA"}
{"Plane":"5546","Time":"6.0", City:"LA"}
{"Plane":"5548","Time":"5.0", City:"CA"}
{"Plane":"5555","Time":"15.0", City:"XA"}
{"Plane":"5555","Time":"8.0", City:"XA"}

还有更多,但我只是可视化数据 我想计算和分组所有的时间和平面,这是预期的输出:

{"_id:":["5546","LA"],"Sum":2,"LateRate":1,"Prob"0.5}

总和一直是总和,迟到总和是总和,时间>“15”,概率是Late/Sum 我试过的代码,但它仍然缺少一些东西:

db.Collection.aggregate([
    {
        $project: {
            Sum: 1,
            Late: {
                $cond: [{ $gt: ["$Time", 15.0] }, 1, 0]
            },
            prob:1
        }
    },
    {
        $group:{
            _id:{Plane:"$Plane", City:"$City"},
            Sum: {$sum:1},
            Late: {$sum: "$Late"}
        }
    },
    {
    $addFields: {
      prob: {
        "$divide": [
          "$Late",
          "$Sum"
        ]
      }
    }
  },
])
db.collection.aggregate([
  {
    $project: {
      Time: 1,
      Late: {
        $cond: [
          {
            $gt: [
              {
                $toDouble: "$Time"
              },
              15.0
            ]
          },
          "$Time",
          0
        ]
      },
      prob: 1,
      Plane: 1,
      City: 1
    }
  },
  {
    $group: {
      _id: {
        Plane: "$Plane",
        City: "$City"
      },
      Sum: {
        $sum: {
          "$toDouble": "$Time"
        }
      },
      Late: {
        $sum: {
          $toDouble: "$Late"
        }
      }
    }
  },
  {
    $addFields: {
      prob: {
        "$divide": [
          "$Late",
          "$Sum"
        ]
      }
    }
  }
])
  1. 项目限制传递给下一阶段的字段
  2. 在字符串上,您无法执行所有 relational/arithmetic 操作

Playground