Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose - sort by array length

I am having this schema

var PostSchema = new Schema({
    title: {type: String, trim: true}
  , description: {type: String, trim: true}
  , votes: [{ type: Schema.ObjectId, ref: 'User' }]
})

I want to sort posts based on votes i.e, I need to sort by array length.

Tried the usual way, but din't work

PostSchema.statics.trending = function (cb) {
  return this.find().sort('votes', -1).limit(5).exec(cb)
}

Any help?

version of mongoose I am using is 2.7.2

like image 951
Madhusudhan Avatar asked Feb 20 '23 18:02

Madhusudhan


1 Answers

You can't do that directly. To be able to sort on array length, you have to maintain it in a separate field (votes_count, or whatever) and update it when you push/pull elements to/from votes.

Then you sort on that votes_count field. If you also index it, queries will be faster.

like image 183
Sergio Tulentsev Avatar answered Mar 03 '23 05:03

Sergio Tulentsev