V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
housne
V2EX  ›  MongoDB

mongodb 分页问题

  •  
  •   housne · Dec 3, 2013 · 4798 views
    This topic created in 4528 days ago, the information mentioned may be changed or developed.
    {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 replies    1970-01-01 08:00:00 +08:00
    YuHong
        1
    YuHong  
       Dec 3, 2013 via iPhone   ❤️ 1
    思路是否不对?
    collection
    .find(null)
    .skip(0)
    .limit(20)
    .sort({id:1})
    .exec(fn)
    housne
        2
    housne  
    OP
       Dec 3, 2013
    @YuHong 嗯,是能用到 skip ,但据说 skip 会很慢,特别是这个数据库比较大的时候
    GitFree
        3
    GitFree  
       Dec 4, 2013 via Android
    如果删除的是不是第一项,skip 0岂不是要跳过第一项
    LeonT
        4
    LeonT  
       Dec 4, 2013
    必须用skip,查询加索引
    loveshouhu
        5
    loveshouhu  
       Dec 11, 2013
    k = g.db.yiyu.find({"title" :{"$ne": ""}})
    loveshouhu
        6
    loveshouhu  
       Dec 11, 2013   ❤️ 1
    上条回复请忽略,手残了。直接按了crtl+enter了。。。

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

    我是这么写的。使用正常。
    删除了也会正常排列的。
    yuanta11
        7
    yuanta11  
       Jan 14, 2014   ❤️ 1
    @YuHong 逻辑上貌似sort应该放在skip + limit前面,这里有个介绍http://mr-ping.com/post/UtTaZsbMyPb4FQT5
    这种方式10W以下数据问题不大
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1217 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 17:55 · PVG 01:55 · LAX 10:55 · JFK 13:55
    ♥ Do have faith in what you're doing.