Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb查询当前记录的上一条和下一条 #231

Open
confidence68 opened this issue Dec 29, 2016 · 0 comments
Open

mongodb查询当前记录的上一条和下一条 #231

confidence68 opened this issue Dec 29, 2016 · 0 comments
Labels

Comments

@confidence68
Copy link
Owner

前言

本博客是很久之前搭建的。前台模板也是很久之前写的,技术方面难免有些过时。代码书写的也比较乱。博客能保持到现在,还多谢各位同学不断的提意见和建议!前几天有同学提出,看博客比较费劲,能否新增上一篇文章和下一篇文章?因此,在原来基础上稍加一些改动,实现了上一页和下一页。因为本博客是nodejs+mongodb书写的,那么,mongodb如何实现查询当前记录的上一条记录和下一条记录呢?

mysql实现方法

mysql查询,网上有很多方法,通常我们用如下方法:

查询上一条记录的SQL语句(如果有其他的查询条件记得加上other_conditions以免出现不必要的错误):

select * from table_a 
    where id = 
        (select id from 
            table_a where id < {$id} [and other_conditions] 
            order by id desc limit 1
        ) 
   [and other_conditions];

查询下一条记录的SQL语句(如果有其他的查询条件记得加上other_conditions以免出现不必要的错误):

select * from table_a 
    where id = 
        (select id from table_a 
            where id > {$id} [and other_conditions] 
            order by id asc limit 1
        ) 
    [and other_conditions];

mongodb实现方法

mongo也可以通过时间或者通过id来判断上一条记录或者下一条记录。我是如下写的:

上一条记录

 db.数据库名称.find({ '_id': { '$lt': ids } }).sort({_id: -1}).limit(1)

下一条记录

db.数据库名称.find({ '_id': { '$gt': ids } }).sort({_id: 1}).limit(1)

另外,可以通过时间字段来查询:

上一条记录

 db.数据库名称.find({ 'created': { '$lt': created } }).sort({_id: -1}).limit(1)

下一条记录

db.数据库名称.find({ 'created': { '$gt': created } }).sort({_id: 1}).limit(1)

实现效果

如下图:

enter image description here

这样可以方便的查询上一条信息和下一条信息了!

希望大家多多为本本站提供一些建设性的已经和建议,本人有时间会按照大家的意见和建议进行修改,网站流量和网站体验都需要大家提出建设性已经,谢谢!上一页下一页意见提出者是@一路下雪 。文章地址:http://www.haorooms.com/post/emmet_s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant