user1710825
user1710825

Reputation: 588

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?

Upvotes: 7

Views: 5342

Answers (1)

shx2
shx2

Reputation: 64318

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

Upvotes: 13

Related Questions