Getting total number of likes that user received by going through all his/her posts MongoDB Getting total number of likes that user received by going through all his/her posts MongoDB mongoose mongoose

Getting total number of likes that user received by going through all his/her posts MongoDB


If this field is going to be shown publicly then I personally recommend that instead of calculating on the fly you pre-calculate it and save it on the user as aggregating data is expensive and should not be a part of your app's logic, especially if this needs to be calculated for each user for the leaderboard feature.

With this said here is how you can calculate it with the aggregation framework

db.replies.aggregate([    {        $match: {            author: userid        }    },    {        $group: {            _id: null,            likes: {$sum: {$size: '$likes'}}        }    }]);

As I said I recommend you do this offline, run this once for each user and save a likeCount field on the user, you can then update your other routes where a like is created to update the user like count using $inc.

// .. new like created ...db.users.updateOne({_id: liked_reply.author}, {$inc: {likeCount: 1}})

And now finding the leaderboard is super easy:

const leaders = await db.users.find({}).sort({likeCount: -1}).limit(10) //top 10?


you can use the models aggregate function to do that:

const userid = 1234post.aggregate([  { $match: { _id: userid } },  { $lookup: {    from: 'Reply',    localField: 'reply',    foreignField: '_id',    as: 'replies'  } },  { $group: {    _id: false,    sumoflikes: { $sum: '$replies.likes' }  } }])

the structure works as follows:

  1. get all the posts from a user with 'userid'
  2. join the table with 'Reply'
  3. sum all of the reply.likes

(it could be that you need to throw in a $unwind: '$replies between 2 and 3 there, i am not 100% certain)