php mongodb 实现group 并按照某字段排序
php- require_once ('../Config.class.php');
- //////////////////
- $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<arr.length;i++){
- for(var j=0;j<arr.length-i-1;j++){
- if(arr[j].age < arr[j + 1].age){
- 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写的比较乱,,自 |