gpt4 book ai didi

PHP MongoDB 计数记录

转载 作者:行者123 更新时间:2023-12-04 12:20:02 25 4
gpt4 key购买 nike

我在 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());
?>

是我的感觉吗?

最佳答案

我找到了一个更好的解决方案 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);

// 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 计数记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42702331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com