PHP MongoDB计数记录 [英] PHP MongoDB Count Records
本文介绍了PHP MongoDB计数记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在php中编写了一个简单的MongoDB查询
I've wrote a simple MongoDB Query in php
计算过去一个小时内的在线总数一切正常
That calculates total online in the past hour everything works fine
但是我觉得这种方式不利于表现
But i feel this way is not good for performance
由于查询本身会自动返回所有匹配数据(因此该查询中不需要数据)
Be cause query it's self return all matches data ( so there is unneeded data in that query )
我需要的只是记录数
我有一个包含数百万个文档的集合
I have a collection that has millions of documents
脚本:
<?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());
?>
我有权利吗?
推荐答案
我找到了一个更好的MongoDB Command解决方案
I've found a much better solution 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);
?>
这篇关于PHP MongoDB计数记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文