Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

Mongodb get top 5 grouped by object

I am using a MERN stack and need to group by certain attribute of schema, so for example: this is my schema,

   const likeSchema = new mongoose.Schema({
   userId: {
       type: Schema.Types.ObjectId,
       ref: 'User'
   },
   commentId: {
       type: Schema.Types.ObjectId,
       ref: 'Comment'
   },
   questionId: {
       type: Schema.Types.ObjectId,
       ref: 'Question'
   }

}, { timestamps: true })

Now, I want to group by questionId and then return the 5 groups with the highest count. So in essence, I want the top 5 posts with the most likes. Is there a way to do this with mongodb?

Any help is appreciated!

question from:https://stackoverflow.com/questions/65878989/mongodb-get-top-5-grouped-by-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can first group by questionId, then sort the result and select the top 5 records.

db.collection.aggregate([{
    "$group": {
        _id: "$questionId",
        userId: {
          $first: "$userId"
        },
        commentId: {
          $first: "$commentId"
        },
        questionId: {
          $first: "$questionId"
        },
        count: {
          $sum: 1
        }
      },
    },
    { $sort: { "count": -1 } },
    { $limit: 5 },
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...