Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

Mongodb is it possible to specify "skip" as the range of index?

In Mongodb for pagination is it possible to specify skip as the range of index, that is suppose I am on page 6, and I want to skip docs from (1-59) and return docs at (0 & 60-70) is it possible to do in a single query.

Upvotes: 1

Views: 243

Answers (1)

mickl
mickl

Reputation: 49945

It is possible to get the data specifying multiple ranges using Aggregation Framework. Every pagination needs to start with $sort to get the data in deterministic order. Then you can use $facet to apply multiple $skip and $limit on sorted data set based on your range. In the next stages you need to $concatArrays from multiple ranges and then use $unwind with $replaceRoot to get original documents shape, try in Mongo shell:

for(var i = 0; i < 100; i++){
    db.col.save({ _id: i })
} 


db.col.aggregate([
    {
        $sort: { _id: 1 }
    },
    {
        $facet: {
            range1: [ { $limit: 1 } ],
            range2: [ { $skip: 60 }, { $limit: 11 } ]
        }
    },
    {
        $project: {
            docs: { $concatArrays: [ "$range1", "$range2" ] }
        }
    },
    {
        $unwind: "$docs"
    },
    {
        $replaceRoot: {
            newRoot: "$docs"
        }
    }
])

outputs:

{ "_id" : 0 }
{ "_id" : 60 }
{ "_id" : 61 }
{ "_id" : 62 }
{ "_id" : 63 }
{ "_id" : 64 }
{ "_id" : 65 }
{ "_id" : 66 }
{ "_id" : 67 }
{ "_id" : 68 }
{ "_id" : 69 }
{ "_id" : 70 }

Upvotes: 1

Related Questions