//////////////////
$mongo = new Mongo(Config::MONGO_CONNECTION_STR);
$mongo->setSlaveOkay(true);
$db = null;
if (!empty($mongo)){
$db = $mongo->selectDB(Config::MONGO_CONNECTION_DB_NAME);
}
$collection = null;
if (empty($db)) {
echo "db null";
exit();
} else {
$collection = $db->CategoryModel;
}
/*$collection->insert(array("category" => "fruit", "age" => 1, "name1" => "apple1"));
$collection->insert(array("category" => "fruit", "age" => 2,"name1" => "apple1"));
$collection->insert(array("category" => "fruit", "age" => 3,"name1" => "apple1"));
$collection->insert(array("category" => "veggie", "age" => 4,"name1" => "apple1"));
$collection->insert(array("category" => "veggie", "age" => 5,"name1" => "apple1"));*/
$keys = array("category" => 1);
$initial = array("items" => array(),"index"=>-1,"total"=>0);
$reduce = "function (obj, prev) {
prev.total++;if(obj.age == 2){
prev.index=prev.items.length+1;}
if(prev.items.length < 2){
prev.items.push(obj);
}
var arr = prev.items;if(arr.length > 0)
{
for(var i=0;i
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;}
}
}
if(arr.length>2){
arr = arr.slice(0,2);
}
}
}";
//$condition = array("category" => array( '$in' => array("fruit")));
$g = $collection->group($keys, $initial, $reduce);
print_r($g);
//////////////////////
demo写的比较乱,,自己整理一下就能看明白,,限制返回分组显示条数,进行冒泡排序需要字段