V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
housne
V2EX  ›  MongoDB

mongodb 分页问题

  •  
  •   housne · 2013-12-03 22:55:29 +08:00 · 4115 次点击
    这是一个创建于 3798 天前的主题,其中的信息可能已经有所发展或是发生改变。
    {id:1, title:xxx}
    {id:2, title:xxx}
    {id:3, title:xxx}
    {id:4, title:xxx}
    {id:5, title:xxx}
    {id:6, title:xxx}
    ...
    ...

    每页会显示20条数据,最开始的写的是 collection.find(id:{$gt:page*20}).limit(20);
    但如果中间删除了一条数据,就会取到 id = 21 , 而第二页的是从 id = 21 开始的,这样就会显示重复的数据 。。。。
    7 条回复    1970-01-01 08:00:00 +08:00
    YuHong
        1
    YuHong  
       2013-12-03 23:06:39 +08:00 via iPhone   ❤️ 1
    思路是否不对?
    collection
    .find(null)
    .skip(0)
    .limit(20)
    .sort({id:1})
    .exec(fn)
    housne
        2
    housne  
    OP
       2013-12-03 23:15:19 +08:00
    @YuHong 嗯,是能用到 skip ,但据说 skip 会很慢,特别是这个数据库比较大的时候
    GitFree
        3
    GitFree  
       2013-12-04 09:30:31 +08:00 via Android
    如果删除的是不是第一项,skip 0岂不是要跳过第一项
    LeonT
        4
    LeonT  
       2013-12-04 12:26:07 +08:00
    必须用skip,查询加索引
    loveshouhu
        5
    loveshouhu  
       2013-12-11 15:23:40 +08:00
    k = g.db.yiyu.find({"title" :{"$ne": ""}})
    loveshouhu
        6
    loveshouhu  
       2013-12-11 15:26:29 +08:00   ❤️ 1
    上条回复请忽略,手残了。直接按了crtl+enter了。。。

    k = db.find({"title" :{"$ne": ""}})
    result = k.sort("post_time", -1).limit(10).skip((start-1)*10)

    我是这么写的。使用正常。
    删除了也会正常排列的。
    yuanta11
        7
    yuanta11  
       2014-01-14 15:18:59 +08:00   ❤️ 1
    @YuHong 逻辑上貌似sort应该放在skip + limit前面,这里有个介绍http://mr-ping.com/post/UtTaZsbMyPb4FQT5
    这种方式10W以下数据问题不大
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   936 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:43 · PVG 06:43 · LAX 15:43 · JFK 18:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.