php操作mongodb 分组排序
1 //连接mongodb
2
3 $db=db("127.0.0.1","27017","db_name");
4
5 //定义临时表和变量
6
7 $temptable="temp_softdownrank";
8
9 $softid="1";
10
11 $softname="a";
12 //删除临时表
13 $mdret=$db->$temptable->drop();
14
15 if($mdret)
16 {
17 //map/reduce 做分组排序
18
19 //要查询的列 用emit生成key=>value进行存储
20
21 $map = new MongoCode("function() { emit(this.softid, {count: 1, softid: this.softid, softname: this.softname}); }");
22
23 //要生成的列
24 $reduce = new MongoCode(
25 "function(key, value) {
26 var result = {count: 0};
27 for(var i=0; i<value.length; i++) {
28 result.count += value[i].count;
29 result.softid = value[i].softid;
30 result.softname = value[i].softname;
31 }
32
33 //返回结果
34 return result;
35 }");
36 //查询条件
37 $findarr=array('successtime'=>array('$lt' => "$endtime",'$gte' => "$startime"),'softid'=>new MongoRegex('/'.$softid.'/'),'softname'=>new MongoRegex('/'.$softname.'/'));
38
39 //生成collection
40 $softrank = $db->command(array(
41 "mapreduce" => "per_pc_softdowndetail",
42 "map" => $map,
43 "reduce" => $reduce,
44 "query" => $findarr,
45 "out" => array("merge" => "$temptable")
46 ));
47
48 $coll = $db->selectCollection($softrank['result']);
49
50 //根据字段进行排序
51 $result = $coll->find()->sort(array("value"=>-1));
52
53 //生成数组
54
55 foreach($result as $key=>$value)
56
57 {
58 $list[] = $value["value"];
59 }
60
61 }
62
63 else
64
65 {}
66
67 //$list 就是所得的数组
一直想做事,却止步于思考。