我想知道如何使用 php 计算这个简单的 mongodb 查询的结果数。
<?php
//connection to mongodb
$collection = new MongoCollection($db, 'User');
$retval = $collection->distinct("age");
var_dump($retval);
?>
如何计算 $retval 变量中有多少结果?
新的聚合框架将使这变得简单: http: //php.net/manual/en/mongocollection.aggregate.php
$project = array('$project'=> array("age"=>1)); //pick only the age field
$group = array('$group'=>array("_id"=>'$age')); //group by age field
$count = array('$group'=>array("_id"=>null,"count"=>array('$sum'=>1))); //count distinct
$result = $collection->aggregate(array($project,$group,$count));
echo $result['result'][0]['count'];
Soory,要知道 $retval 中有多少结果很简单。写这个:
echo count($retval);
我的解决方案返回一项区分的子项的计数。不是简单的不同集合的计数^^
例如,如果您有这些数据:
Age: | User:
--------------
{ "age":"20", "name":"David" },
{ "age":"20", "name":"Goerge" },
{ "age":"22", "name":"tiffany" }
我的解决方案返回一个数组,当你每个这个数组时,例如:
foreach ($retval as $row)
echo($row['age'] . ': ' . $row['count'] . "\n");
返回的数据:
20 : 2
22 : 1
MongoDB 的 PHP 文档描述了如何在获取集合中计数:http ://www.php.net/manual/en/mongocollection.count.php
为了对不同的结果进行计数,您可以在组收集中创建一个 map-reduce,例如以下示例:
<?php
$retval = $collection->group(
array('age' => true), // field(s) to group by
array('count' => 0),
new MongoCode('function(doc, prev) { prev.count += 1 }'),
array(null) // condition
);
?>
这
new MongoCode(..)
函数将当前文档和聚合带到这一点并进行聚合。最后你可以得到计数:
print($retval["count"]);
$collection = new MongoCollection($db, 'contacts');
$keys = array("Department" => 1);
// set intial values
$initial = array("count" => 0);
// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";
// only use documents where the "state" field is ar
$condition = array('condition' => array("State" => 'AR'));
$results = $collection->group($keys, $initial, $reduce, $condition);
foreach ($results['retval'] as $key => $value) {
echo 'Contacts in state AR with department '.$value['Department'] . ' are:'. $value['count'];
echo '<br />';
}