0

A bit new to Mongo here. I want to return a subset of a collection using find(), but from a specified "starting point". I have a dictionary-like list of documents that I return in chunks and in alphabetical order via the sort and limit parameters, but it always starts at the beginning of the collection.

I want to be able to add a "starts with" parameter to the find() method so that, for example, if I queried the letter "h" it would return all documents but with the first one returned being the first document starting with "h". Using next() would eventually return documents starting with "i", "j", "k", and so on. I also haven't been able to find any uses or hacks to allow for a "previous()" method that does the opposite of next(). I'd like to use "previous()" (or whatever it may be called), to return documents starting with "g", "f", all the way back to the beginning of the collection.

Am I barking up the right tree? This seems like a pretty obvious function of a database, but I haven't found any examples or other mention of using Mongo like this.

Community
  • 1
  • 1
Pete
  • 502
  • 5
  • 14

1 Answers1

1

The starting point of your cursor is simply the first document in the result set, which is based on the filtering and sorting of your query.

So if you have a collection of docs with a name field, you can get the docs starting with the ones with a name beginning with 'h', by using the $gte operator and then sorting ascending on name:

db.test.find({name: {$gte: 'h'}}).sort({name: 1})

Now, cursors only move forward, so if you want to go in the opposite direction, you have to use a new query that flips things around:

db.test.find({name: {$lt: 'h'}}).sort({name: -1})
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Brilliant, I think this is what I need. It wasn't clear from the docs that cursors couldn't move backward, which is why the lack of a "previous()" method was confusing. – Pete Oct 02 '15 at 02:05