Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit length of selected array by Mongoose find

Here I have a document with an array as one filed in it. Looks like:

var UserSchema = new mongoose.Schema({
    activities:[{
        action:String,
        time:Number,
        extraInfo:{}
    }]
})

And now I want to select this array,

UserModel
 .findById(user._id)
 .select('activities')
 .lean()
 .exec((err,user)=>{....})

but I just need the latest, like 20, activity records.

is there any way to limit the length of selected array?

like image 796
Yangxiao Ou Avatar asked Feb 07 '23 07:02

Yangxiao Ou


1 Answers

You can use the MongoDB $slice operator: https://docs.mongodb.org/manual/reference/operator/projection/slice/#slice-projection

Mongoose has a helper function to achieve this: http://mongoosejs.com/docs/api.html#query_Query-slice

So, your example become something like that:

UserModel
  .findById(user._id)
  .slice('activities', 20)
  .select('activities')
  .lean()
  .exec((err,user)=>{....})
like image 141
Sandro Munda Avatar answered Feb 16 '23 04:02

Sandro Munda