【问题标题】:MongoDB limit and number of documents returnedMongoDB 限制和返回的文档数
【发布时间】:2014-08-21 00:40:17
【问题描述】:

我有以下 Mongo 数据库:

db.group:

{id: 1, name:"a"}  // index == 1
{id: 2, name:"b"}  // index == 2
{id: 13, name:"c"} // index == 3
{id: 14, name:"d"} // index == 4
{id: 51, name:"e"} // index == 5
{id: 52, name:"f"} // index == 6
{id: 61, name:"g"} // index == 7
{id: 88, name:"h"} // index == 8

我正在实现分页,我想返回 3 个文档,从索引 4 开始(从 1 开始,而不是从零开始),这将是

{id: 14, name:"d"} // index == 4
{id: 51, name:"e"} // index == 5
{id: 52, name:"f"} // index == 6

我知道我可以使用.limit 来限制返回的记录数,但是我怎么说limit 应该从索引4 开始?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    你可以使用cursor.skip():

    db.getCollection('group').sort({_id: 1}).skip(3).limit(10)
    

    请注意,随着数量的增加,skip() 并不是最有效的。您可能想改用基于范围的分页:

    db.getCollection('group').find({_id: {$gt: 13}}).limit(10)
    

    【讨论】:

    • 您的第一个示例应该包含一个明确的排序顺序(看起来应该是name),因为不能保证自然顺序。另请参阅:What does Mongo sort on when no sort order is specified?。另外,我希望您会发现group 不能作为mongo shell 的集合名称,因为它与group() 函数重叠。可以使用db.getCollection() 解决;您当前的语法会导致错误。
    • 我在这里是因为我还将我的集合命名为“组”,并且未能在 mongo shell 中调用 find 方法。我认为这个答案如果明确提到它会帮助更多的人。 :)
    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2018-03-26
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多