How can i find most occuring userId, which lies inside [] using mongoose aggregation ?? Nodejs, Expressjs

Viewed 43

So the situation is, i have a students and teachers collection, each student object has a property called fav which is an array of ObjectId referring to documents in teachers collection, Now i wanna find out most occurring teacher among all students fav property How can i do that ?? How can I use mongoose aggregation to work my way around this ?? I have tried couple of solutions but doesnt work very been stuck on this for a while now,

1 Answers

If you only want the top N teachers (N << n), one option is to start from the students collection and use $lookup to bring the teachers:

db.students.aggregate([
  {$project: {_id: 0, fav: 1}},
  {$unwind: "$fav"},
  {$group: {_id: "$fav", count: {$sum: 1}}},
  {$sort: {count: -1}},
  {$limit: N},
  {$lookup: {
      from: "teachers",
      localField: "_id",
      foreignField: "_id",
      as: "count"
  }},
  {$project: {_id: 0, result: {$first: "$count"}}},
  {$replaceRoot: {newRoot: "$result"}}
])

See how it works on the playground example - top N

But if you want to find out the count for many teachers, another option is to start from the teachers collection and bring the number of students: playground example - many teachers

Related