search

Home  >  Q&A  >  body text

nosql - MongoDB 如何获取某条记录的相邻记录

比如获取某篇文章的前一篇和后一篇记录,有时间字段created

尝试使用下列语句获取文章

# created 是当前文章的创建时间
# 前一篇
prev_post = db.Post.find({ 'created': { '$lt': created } }, sort = [('created', -1)], limit = 1)
# 后一篇
next_post = db.Post.find({ 'created': { '$gt': created } }, sort = [('created', 1)], limit = 1)

运行的结果是这些记录是跳跃使的,有时候中间会跳过好几条记录,不知道如何解决这个问题
我想可能是我对 find 的理解有误,希望大家指点迷津

PHPzPHPz2799 days ago698

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-21 10:58:25

    First of all, there is no problem with the statement, but you used the time type.
    If the time type is used, it is likely that the time records are the same. Check whether your records have the same time.
    If conditions permit, you can use _id或者配合_id to avoid this situation.

    reply
    0
  • Cancelreply