Pymongo 聚合管道

时间:2021-04-20 04:13:55

标签: python mongodb mongodb-query aggregation-framework

修改问题。会尽快更新。

1 个答案:

答案 0 :(得分:2)

演示 - https://mongoplayground.net/p/ksay82IaGHs

TeacherIDTeacherID 分组并获取组合的出现次数,$sort by occurrence 按降序排列。

db.collection.aggregate([
  { $group: { _id: { TeacherID: "$TeacherID", StudentID: "$StudentID" }, occurrence: { $sum: 1 } } },
  { $sort: { "occurrence": -1 } }
]);

输出
[
  {
    "_id": {
      "StudentID": 2,
      "TeacherID": 212
    },
    "occurrence": 3
  },
  {
    "_id": {
      "StudentID": 4,
      "TeacherID": 223
    },
    "occurrence": 1
  }, .....
 ]

如果你想要最高记录

演示 - https://mongoplayground.net/p/zBsGdAOdYwy

  {
    "$limit": 1
  }

演示 - https://mongoplayground.net/p/G2KIVcjtYII

如果您想检查特定的 TeacherID,请使用 $match