简体   繁体   中英

Pymongo aggregate pipeline

REVISING question. Will be updated soon.

Demo - https://mongoplayground.net/p/ksay82IaGHs

Group by TeacherID and TeacherID and get occurrence of the combination, $sort by occurrence in descending order.

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

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

If you want the top record

Demo - https://mongoplayground.net/p/zBsGdAOdYwy

 { "$limit": 1 }

Demo - https://mongoplayground.net/p/G2KIVcjtYII

If you want to check for specific TeacherID use $match

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM