'Get trending groups using mongodb aggregation

I have two collections, Group and GroupChat. A group has a chatroom respectively.

// group.model

{
 name: string,
 desc: string
}

// group.chat.model

{
 group: {type: Schema.Types.ObjectId, ref: 'Group'},
 sender: ObjectId
 message: String
}

Now I want to determine the top 4 trending groups based on these two criteria.

  1. Highest number of followers in a group
  2. most chats in a group.

I am trying to use MongoDB aggregate to do this because I know it is possible but I am currently stuck in coming up with the right pipeline query to achieve this. How do I go about this? Any help is appreciated.

Here is a snippet of my pipline (which is wrong)

const pipeline = [
 { $match: { name: { $exists: true } } },
 { $lookup: { from: 'groupchats', localField: '_id', foreignField: 'group', as: 'groupchat' } },
 { $unwind: { path: '$groupchat', preserveNullAndEmptyArrays: true } },
 { $sortByCount: '$groupchat.group' },
  { $sort: { createdAt: 1 } },
 { $limit: 5 },
];


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source