【问题标题】:PHP MongoDB Count RecordsPHP MongoDB 计数记录
【发布时间】:2017-03-09 17:59:09
【问题描述】:

我用 php 写了一个简单的 MongoDB 查询

计算过去一小时的在线总数 一切正常

但我觉得这种方式对性能不好

因为查询它会自行返回所有匹配数据(因此该查询中有不需要的数据)

我需要的只是记录数

我有一个包含数百万文档的集合

脚本:

<?php
    // Last Online Time
    $Time = time() - 86400;

    // Connection
    $Manager = new MongoDB\Driver\Manager("mongodb://" . DB_USERNAME . ":" . DB_PASSWORD . "@" . DB_HOST . ":" . DB_PORT . "/" . DB_NAME);

    // Query
    $Query = new MongoDB\Driver\Query(['LastOnlineTime' => ['$gt' => (int) $Time]], []);

    // Result
    $Result = $Manager->executeQuery(DB_NAME . "." . $Collection, $Query);

    // Get Total Online In 1 Hour Ago
    echo count($Result->toArray());
?>

我的感觉有权利吗?

【问题讨论】:

    标签: php mongodb database


    【解决方案1】:

    我找到了一个更好的解决方案 MongoDB Command

    这里是

    <?php
        // Last Online Time
        $Time = time() - 86400;
    
        // Connection
        $Manager = new MongoDB\Driver\Manager("mongodb://" . DB_USERNAME . ":" . DB_PASSWORD . "@" . DB_HOST . ":" . DB_PORT . "/" . DB_NAME);
    
        // Command
        $Command = new MongoDB\Driver\Command(["count" => "account", "query" => ['LastOnline' => ['$gt' => (int) $Time]]]);
    
        // Result
        $Result = $Manager->executeCommand(DB_NAME, $Command);
    
        //print($Result->toArray());Array ( [0] => stdClass Object ( [n] => 228598 [ok] => 1 ) //so n is our totalcount
        // Get Total Online In 1 Hour Ago
        echo count($Result->toArray()[0]->n);
    ?>
    

    【讨论】:

    • 这个答案可能受益于对命令中的元素在做什么的解释。
    • 如果你限制结果,答案会是错误的,因为如果你有更多的结果没有返回,你的答案会给出限制值。
    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多