Mongoose: aggregate with skip can't work

Created on 16 May 2014  路  6Comments  路  Source: Automattic/mongoose

Hi, guys, please help me out, thank you very much!

Schema

ReportSchema = new Schema
  user:type:Schema.ObjectId,ref:'User',index:sparse:true
  report:[
    qid:type:Schema.ObjectId,ref:'Question'
    value:Schema.Types.Mixed
    remark:String
  ]
  created_at:Date

Aggregate when skip=0 works fine, but when skip!=0, I got nothing. I'm sure there're pages data.

Report.aggregate()
    .unwind('report')
    .match('report.qid':new ObjectId(data.qid))
    .project(
      value:'$report.value'
      remark:'$report.remark'
      user:'$user'
    )
    .sort('created_at':-1)
    .limit(limit)
    .skip(skip)
    .exec (err, result)->
help

Most helpful comment

I resolved this to make skip before limit, is it a bug?

.skip(skip)
.limit(limit)

All 6 comments

I resolved this to make skip before limit, is it a bug?

.skip(skip)
.limit(limit)

It's because if you limit first you can't skip after, if skip > limit you end up out of the limit results so no data.

@mypawdesign is right. In aggregate, $limit limits the number of documents sent to the next aggregation state, and $skip skips the first N documents, so if $skip is after $limit and $skip >= $limit, you won't get any results. In short, this is expected behavior in MongoDB.

@mani95lisa Thanks for the trick . and @vkarpov15 , you are right . Seems like expected behavior in mongodb .

Hi @mani95lisa
This is how to fix:
db.collection.aggregate([{$match}, {$sort: {}}, {$skip: _skip}, {$limit: _limit}, {$project: {}}])
Hope it's useful for you!

@mani95lisa thanks dear, it's working now

Was this page helpful?
0 / 5 - 0 ratings