I am making an image gallery. Each image has an _id and when I'm viewing an image I want the next 3 images and 3 before. How can I get this in a mongodb query? I think that I can use sort by _id because this is unsortable. Maybe with mapReduce or some specific query?
Asked
Active
Viewed 5,287 times
7
-
Possible duplicate of [Finding The Next Document in MongoDb](http://stackoverflow.com/questions/12012253/finding-the-next-document-in-mongodb) – Ulysse BN Feb 02 '17 at 06:23
1 Answers
13
Yes, you can sort by _id
. Use two queries: one for the 3 before and one for the 3 after.
An example in python:
my_id = coll.find()[20]['_id']
coll.find({ '_id': {'$lt': my_id}}).sort([('_id', -1)]).limit(3) # before
coll.find({ '_id': {'$gt': my_id}}).sort('_id').limit(3) # after

shx2
- 61,779
- 13
- 130
- 153