Get all the entries between two other entries in MongoDB
Problem
I have a Mongodb collection with objects, the _id property of which is a string.
I want to perform a .find() operation on that collection, perform a .sort() to the returned cursor. Then, an operation of .toArray() would give me an array of documents in a particular order. However, I do not want to extract all those documents, but only the ones between two of them.
Now, I understand that I can perform a .toArray(), get all my results in an array, and then select the interval between two documents, but that would cost too much resources. I want, if possible, to select that interval BEFORE performing an .toArray(), or in general, in the most resource-saving way.
What I am trying to accomplish is an alternative of .limit() and .skip() (paging), but pinpointing an interval by providing _id's of "starting" and "ending" document.
E.g. given that .find().sort({_id: 1}).toArray()
gives:
{_id: "a", a: "First entry"},
{_id: "bar", a: "Third entry"},
{_id: "bar2", a: "Fourth entry"},
{_id: "bar3", a: "Fifth entry"},
{_id: "bar4", a: "Sixth entry"},
{_id: "foo", a: "SEcond entry"}
I need something like
find().sort({_id: 1}).allAfter({_id: "bar"}).allBefore({_id: "bar4"}).toArray(...);
To give me:
{_id: "bar2", a: "Fourth entry"},
{_id: "bar3", a: "Fifth entry"},
Solution
What you are talking about is range based pagination (where the range is on the sort). You can do this easily by keeping track of the edge of the previous and next pages. Here are some existing answers:
Range based paging mongodb
How to do pagination using range queries in MongoDB?
http://groups.google.com/group/mongodb-user/browse_thread/thread/dc46592112735bf0/a5c700b1283537d8
Let me know if this is not sufficient for your needs.
Discussion
View additional discussion.