【问题标题】:MongoDB count and resultsMongoDB 计数和结果
【发布时间】:2015-12-09 10:26:44
【问题描述】:

如果有人可以帮助我,我将不胜感激:我需要对数据库进行正常查询,但是由于我的集合非常大(10000 个文档),我需要进行查询并使用 $limit 和 @ 987654323@。那部分我解决了,但现在我想计算所有文件,即使返回的文件更少。输出应该是这样的:

{
     count: 1150,
     data: [/*length of 50*/]
}

有人可以帮忙吗?非常感谢。

【问题讨论】:

标签: javascript mongodb mongodb-query


【解决方案1】:

既然您提到您正在进行正常查询,那么进行聚合是不明智的。 find() 在这里将是一个更好的选择。相反,您可以使用 find 查询本身。在 mongoDB 控制台中执行此操作的命令如下所示:

> var docs = db.collection.find().skip(10).limit(50)
> docs.count()
189000
> docs.length()
50

【讨论】:

    【解决方案2】:

    您可以使用一个查询本身来执行此操作。在 Node.js 和 Express.js 中,您必须像这样使用它才能使用“计数”函数以及 toArray 的“结果”。

    var curFind = db.collection('tasks').find({query});
    

    然后你可以像这样在它之后运行两个函数(一个嵌套在另一个中)

    curFind.count(function (e, count) {    
    // Use count here    
        curFind.skip(0).limit(10).toArray(function(err, result) {    
        // Use result here and count here    
        });
    });
    

    【讨论】:

    • 在 mongodb 3.x 中这仍然有效吗?我得到 toArray 不是函数
    【解决方案3】:

    我认为不使用聚合就不可能在单个查询中获得结果的总数以及分页数据。

    您可能可以通过聚合来实现这一点,但既然您提到,您的集合非常大,您应该避免它并将查询分成两部分。我正在为您提供一个示例,说明 user 集合的 rating 字段包含超过 10,000 条记录:

    var finalResult = {};
    
    var query = {
        rating: {$gt: 2}
    };
    
    // Get first 50 records of users having rating greater than 2
    var users = db.user.find(query).limit(50).skip(0).toArray();
    // Get total count of users having rating greater than 2
    var totalUsers = db.user.cound(query);
    
    finalResult.count = totalUsers;
    finalResult.data = users;
    

    你的最终输出可能是这样的:

    finalResult == {
         count: 1150,
         data: [/*length of 50 users*/]
    }
    

    希望,这对你有意义。 Grails 等一些著名的技术在内部实现了分页。

    另一种更简洁的方法可能是:

    var finalResult = {};
    
    var query = {
        rating: {$gt: 2}
    };
    
    var cursor = db.user.find(query).limit(50).skip(0);
    // Get total count of users having rating greater than 2
    // By default, the count() method ignores the effects of the cursor.skip() and cursor.limit()    
    finalResult.count = cursor.count();;
    finalResult.data = cursor.toArray();
    

    【讨论】:

      【解决方案4】:

      正如Sarath Nair 所述,您可以使用计数,因为它忽略了跳过和限制。检查:MongoDB Count

      顺便说一句,这是另一个 StackOverflow 问题的重复:Limiting results in MongoDB but still getting the full count?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 1970-01-01
        • 2015-11-07
        • 2020-07-18
        • 1970-01-01
        相关资源
        最近更新 更多