【问题标题】:Pymongo aggregate pipelinePymongo 聚合管道
【发布时间】:2021-04-20 04:13:55
【问题描述】:

我想使用聚合管道来获取给定另一个值的最常见值。

如何使用聚合管道查找 TeacherId 212 最常见的 StudentId?

一直在尝试下面的代码,但没有得到想要的结果。

pl= [
        '$project': {
            '_id': 1,
            'StudentId': 1,
            "TeacherID: 1,
            "$group": {
            "__id":  'TeacherID',
            "__id": {
              "$first": "StudentID",
        }
    }
}
]

db.collection.aggregate(pl)

【问题讨论】:

  • 请按承诺更新问题。当您通过搜索引擎找到一个不存在的问题的赞成和接受的答案时,这不是很好...... :)

标签: python mongodb mongodb-query aggregation-framework


【解决方案1】:

演示 - 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

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 2020-10-26
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多