Nguyen Phong
Nguyen Phong

Reputation: 71

I want to get the 20 records with the highest number of views + likes, how do I do in mongoose?

I have a schema below:

enter image description here

I want to get the 20 records with the highest number of views + likes, how do I do in mongoose?

Upvotes: 0

Views: 224

Answers (2)

Rakshith Murukannappa
Rakshith Murukannappa

Reputation: 589

You can use project to get the number of likes and pipe it with another project and add the views and likes.

db.demo.aggregate([{
  $project: {
    likes: {
      $size: "$likes"
    },
    views: 1,
  }
}, {
  $project: {
    total: {
      $add: [
        "$likes", "$views"
      ]
    }
  }
},{ 
  $sort : { 
    total : -1
  } 
},{ 
  $limit : 20 
}])

Upvotes: 1

Егор Лебедев
Егор Лебедев

Reputation: 1336

as I know there is no way to do that in one operation, but you could add a separate field with views + likes, and user sort desc + limit: 20

Upvotes: 0

Related Questions