Next and previous documents

匆匆过客 提交于 2020-01-13 12:49:05

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/19123483/next-and-previous-documents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!