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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With