![](/img/trans.png)
[英]MongoDB PHP count $within method extremely slow for large datasets
[英]Count too slow in MongoDB with PHP
我試圖用計數行檢查我的代碼。 但是這段代碼工作非常緩慢。 我如何優化此代碼? 反正還有數嗎?
$find = $conn_stok->distinct("isbn");
for($i=0;$i<=25; $i++) {
$isbn = $find[$i];
$countit= $conn_kit->find(array('isbn'=>$isbn))->count();
if($countit> 0){
echo "ok<br>";
} else {
echo "error<br>";
}
}
看起來您正在嘗試按照舊的SQL語言進行簡單的count(*)分組。 在MongoDB中,您將使用聚合框架讓數據庫為您完成工作,而不是在代碼中完成工作。
聚合框架管道如下所示:
db.collection.aggregate({$group:{_id:"$isbn", count:{$sum:1}}}
如果需要幫助,我將讓您將其翻譯為PHP,這里有很多示例。
您似乎要計算25個使用最多的ISBN的數量,並計算使用頻率。 在PHP中,您將運行以下查詢。 第一個查找所有ISBN,第二個是執行分組的聚合命令。
$find = $conn_stok->distinct( 'isbn' );
$aggr = $conn_kit->aggregate(
// find all ISBNs
array( '$match' => array( 'isbn' => array( '$in' => $find ) ) ),
// group those
array( '$group' => array( '_id' => '$isbn', count => array( '$sum' => 1 ) ) ),
// sort by the count
array( '$sort' => array( 'count' => 1 ) ),
// limit to the first 25 items (ie, the 25 most used ISBNs)
array( '$limit' => 25 ),
)
(對於$ conn_stok和$ conn_kit包含什么以及要作為答案,您有點含糊不清。如果可以以此來更新您的問題,我可以更新答案)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.