Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next and previous documents

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?

like image 628
user1710825 Avatar asked Oct 01 '13 18:10

user1710825


1 Answers

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
like image 112
shx2 Avatar answered Dec 12 '22 20:12

shx2