MongoDB - 按条件分组并查找前 N 个

MongoDB - Group and Find Top N with condition

考虑这个测试集合,其中机场由 AirportID:

标识
[
    { AirportID:"1001", delayMinutes :"15.0" },
    { AirportID:"1004", delayMinutes :"3.0" },
    { AirportID:"1001", delayMinutes :"20.0" },
    { AirportID:"1002", delayMinutes :"6.0" },
    { AirportID:"1002", delayMinutes :"25.0" },
    { AirportID:"1004", delayMinutes :"55.0" },
]

我想将它组合在一起并列出该列表中的前 2 个,条件是 $delayMinutes 大于“10.0”。 我想将它组合在一起并列出该列表中的前 2 个。

我试过的代码:

db.test.aggregate([
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: {
          "$toDouble": "$delayMinutes"
        }
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

随着要求的明确,

您需要先 过滤文档 delayMinutes 字段大于 ($gt) 10.

确保在比较之前将 delayMinutes 转换为 double

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            "$toDouble": "$delayMinutes"
          },
          10
        ]
      }
    }
  },
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: {
          "$toDouble": "$delayMinutes"
        }
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

Sample Mongo Playground


并且您可以将 delayMinutes 字段更新为 $set 阶段的两倍。因为它在 $match$group 阶段是多余的。

db.collection.aggregate([
  {
    $set: {
      delayMinutes: {
        "$toDouble": "$delayMinutes"
      }
    }
  },
  {
    $match: {
      $expr: {
        $gt: [
          "$delayMinutes",
          10
        ]
      }
    }
  },
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: "$delayMinutes"
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

Sample Mongo Playground (with $set)