Home > Blockchain >  Nodejs: mongoose skip in aggregate does not work correct
Nodejs: mongoose skip in aggregate does not work correct

Time:12-29

And I have 2 documents in my database.

So, When $skip is 0, data return one document.

const data = await MyData.aggregate([
    { $limit: 1 },
    { $skip: 0 },
  ])

But if I change $skip to 1, data return empty array!

const data = await MyData.aggregate([
    { $limit: 1 },
    { $skip: 1 },
  ])

And if I change $limit to 2, data return two documents!

const data = await MyData.aggregate([
    { $limit: 2 },
    { $skip: 0 },
  ])

CodePudding user response:

Order matters.

When you don't have a $match at the start of the pipeline, there will be an implicit collection scan that reads all the documents in the collection.

When the {$limit: 1} stage begins, all of the documents will be in the pipeline, when it completes, the output will be a single document, which is passed on to the next stage.

The {$skip: 1} stage then skips the first document, and finding nothing else, returns an empty result set.

The solution here is to skip first, then limit.

  • Related