Search code examples
mongodbcursor

Iterate over cursor with offset


I have got following data:

{ _id: "aaa" }
{ _id: "aab" }
{ _id: "aav" }
{ _id: "baa" }
{ _id: "bac" }
{ _id: "bad" }

I want to get my cursor to, lets say, documents starting on b and iterate to the end.

Pseudocode

cursor.offset(_id: "b").each{ |doc| puts doc }
#=> { _id: "baa" }
#=> { _id: "bac" }
#=> { _id: "bad" }

As far as MongoDB stores indexes in B-Tree it should be possible somehow :)


Solution

  • Just search for all documents >= "b":

    db.collection.find( { _id: { $gte: "b" } } );
    

    And then iterate over the result set.