mongodb 分组查询

数据的保存

  1. include_once ‘mDB.class.php‘;
  2. $m=new mDB();
  3. $m->setDB(‘mydb‘);
  4. // $m->save(‘stu‘,[‘dept‘=>‘财务‘,‘name‘=>‘张三‘,‘age‘=>73]);
  5. // $m->save(‘stu‘,[‘dept‘=>‘计算机‘,‘name‘=>‘张四‘,‘age‘=>53]);
  6. // $m->save(‘stu‘,[‘dept‘=>‘计算机‘,‘name‘=>‘张五‘,‘age‘=>23]);
  7. // $m->save(‘stu‘,[‘dept‘=>‘财务‘,‘name‘=>‘张六‘,‘age‘=>93]);
  8. // $m->save(‘stu‘,[‘dept‘=>‘计算机‘,‘name‘=>‘张七‘,‘age‘=>83]);
  9. // $m->save(‘stu‘,[‘dept‘=>‘法学‘,‘name‘=>‘张八‘,‘age‘=>53]);

查询出所有的专业

  1. $db=$m->getMongoClient();
  2. $d=$db->mydb;
  3. $c=$d->stu;
  4. // echo $c->find([‘dept‘=>‘计算机‘])->count();//返回计算机专业有几人
  5. $currsor=$c->find([],[‘_id‘=>0,‘dept‘=>1]);
  6. foreach ($currsor as $v){
  7. echo $v[‘dept‘].‘<br>‘;
  8. }

消除重复取出各个专业的名字distinct

  1. $db=$m->getMongoClient();
  2. $d=$db->mydb;
  3. $c=$d->stu;
  4. $depts=$c->distinct(‘dept‘);
  5. foreach ($depts as $v){
  6. echo $v.‘<br>‘;
  7. }

统计各个专业的人数

  1. include_once ‘mDB.class.php‘;
  2. $m=new mDB();
  3. $m->setDB(‘mydb‘);
  4. $db=$m->getMongoClient();
  5. $d=$db->mydb;
  6. $c=$d->stu;
  7. $depts=$c->distinct(‘dept‘);
  8. foreach ($depts as $v){
  9. echo $v;
  10. echo ‘专业人数‘.$c->find([‘dept‘=>$v])->count();
  11. echo ‘<hr>‘;
  12. }

分组查询的所有代码

  1. <?php
  2. header(‘content-type:text/html;charset=UTF-8‘);
  3. //无密码直接登录mongodb
  4. $m = new MongoClient(‘mongodb://localhost:27017‘);
  5. $db = $m->selectDB(‘aaa‘);
  6. $c1 = $db->student;
  7. //$c1->insert(array("category" => "计算机", "name" => "张在",‘age‘=>33));
  8. //$c1->insert(array("category" => "计算机", "name" => "李四",‘age‘=>25));
  9. //$c1->insert(array("category" => "英语", "name" => "赵六",‘age‘=>30));
  10. //$c1->insert(array("category" => "英语", "name" => "赵七",‘age‘=>40));
  11. //$c1->insert(array("category" => "会计", "name" => "李勇",‘age‘=>10));
  12. //$keys = array("category" => 1);
  13. //$initial = array("items" => array());
  14. //$reduce = "function (obj, prev) { prev.items.push(obj);}";
  15. //$reduce = "function (obj, prev) { prev.items.push(obj.name);}";
  16. //$reduce = "function (obj, prev) { prev.items.push(obj.name+obj.age);}";
  17. //$g = $c1->group($keys, $initial, $reduce);
  18. //echo json_encode($g[‘retval‘]);
  19. //echo ‘<pre>‘;
  20. //print_r($g);
  21. //统计各专业人数
  22. // $keys = array("category" => 1); //指定分类属性
  23. // $initial = array("count" => 0);
  24. // $reduce = "function (obj, prev) { prev.count++; }";
  25. // $condition = array(‘condition‘ => array());//条件
  26. // $g = $c1->group($keys, $initial, $reduce, $condition);
  27. // var_dump($g);
  28. //统计年龄大于等于25岁的总人数
  29. // $keys=[];
  30. // $initial = [‘c‘=>0];
  31. // $reduce = ‘function(obj,prev){prev.c++;}‘;
  32. // $where = [‘condition‘=>[‘age‘=>[‘$gte‘=>25]]];
  33. // $g = $c1->group($keys,$initial,$reduce,$where);
  34. // var_dump($g);
  35. //求出各专业学生年龄之和 select category,sum(age) from student group by category;
  36. // $keys=[‘category‘=>1];
  37. // $initial = [‘sum‘=>0];
  38. // $reduce = "function(obj,prev){prev[‘sum‘] += obj.age; }";
  39. // $g = $c1->group($keys,$initial,$reduce);
  40. // var_dump($g);
  41. //根据专业,来统计各专业的最大年龄
  42. // $keys=[‘category‘=>1];
  43. // $initial = [‘max‘=>0];
  44. // $reduce = "function(obj,prev){if(obj.age>prev[‘max‘]){prev[‘max‘]=obj.age;} }";
  45. // $g = $c1->group($keys,$initial,$reduce);
  46. // var_dump($g);
  47. //根据专业分组,求出每个专业的人数,平均年龄,年龄总各
  48. $keys=[‘category‘=>1];
  49. $initial = [‘sum‘=>0,‘count‘=>0,‘avg‘=>0];
  50. $reduce = "function(obj,prev){prev[‘sum‘] += obj.age;prev[‘count‘]++;prev[‘avg‘]=prev[‘sum‘]/prev[‘count‘]}";
  51. $g = $c1->group($keys,$initial,$reduce);
  52. var_dump($g);
  53. $m->close();

查询出所有的信息

  1. include_once ‘mDB.class.php‘;
  2. $m=new mDB();
  3. $m->setDB(‘mydb‘);
  4. $db=$m->getMongoClient();
  5. $d=$db->mydb;
  6. $c=$d->stu;
  7. $keys = ["dept" => 1]; //指定分类属性
  8. $initial = array("count" => 0);
  9. $reduce = "function (obj, prev) { prev.count++; }";
  10. $condition = array(‘condition‘ => array());//条件
  11. $g = $c->group($keys, $initial, $reduce, $condition);
  12. echo ‘<pre>‘;
  13. var_dump($g);

统计出所有的信息

$reduce = "function (obj, prev) { prev.count++; }";此句为程序里面的死命令

  1. <?php
  2. include_once ‘mDB.class.php‘;
  3. $m=new mDB();
  4. $m->setDB(‘mydb‘);
  5. $db=$m->getMongoClient();
  6. $d=$db->mydb;
  7. $c=$d->stu;
  8. $keys = ["dept" => 1]; //指定分类属性
  9. $initial = array("count" => 0);
  10. $reduce = "function (obj, prev) { prev.count++; }";
  11. $condition = array(‘condition‘ => array());//条件
  12. $g = $c->group($keys, $initial, $reduce, $condition);
  13. echo ‘<pre>‘;
  14. var_dump($g);
  15. echo ‘总人数‘.$g[‘count‘];
  16. echo ‘<br>总专业‘.$g[‘keys‘].‘个专业<br>‘;
  17. foreach ($g[‘retval‘] as $v){
  18. echo $v[‘dept‘].‘人数‘.$v[‘count‘].‘人‘;
  19. }

"function(obj,prev){

prev[‘sum‘] += obj.age;

prev[‘count‘]++;

prev[‘avg‘]=prev[‘sum‘]/prev[‘count‘];

if(obj.age>prev[‘max‘]){prev[‘max‘]=obj.age;}

if(obj.age<prev[‘min‘]){prev[‘min‘]=obj.age;}

}";

求出平均分,最高分,最低分,各专业的总分

  1. <?php
  2. include_once ‘mDB.class.php‘;
  3. $m=new mDB();
  4. $m->setDB(‘mydb‘);
  5. $db=$m->getMongoClient();
  6. $d=$db->mydb;
  7. $c=$d->stu;
  8. //根据专业分组,求出每个专业的人数,平均年龄,年龄总各
  9. $keys=[‘dept‘=>1];
  10. $initial = [‘sum‘=>0,‘count‘=>0,‘avg‘=>0,‘max‘=>0,‘min‘=>100];
  11. $reduce ="function(obj,prev){
  12. prev[‘sum‘] += obj.age;
  13. prev[‘count‘]++;
  14. prev[‘avg‘]=prev[‘sum‘]/prev[‘count‘];
  15. if(obj.age>prev[‘max‘]){prev[‘max‘]=obj.age;}
  16. if(obj.age<prev[‘min‘]){prev[‘min‘]=obj.age;}
  17. }";
  18. $g = $c->group($keys,$initial,$reduce);
  19. echo ‘<pre>‘;
  20. var_dump($g);
  21. foreach ($g[‘retval‘] as $v){
  22. echo $v[‘dept‘].‘平均分‘.$v[‘avg‘].‘最高分‘.$v[‘max‘].‘最低分‘.$v[‘min‘].‘各专业总分为‘.$v[‘sum‘].‘<br>‘;
  23. }

来自为知笔记(Wiz)

时间: 2024-10-05 03:02:22

mongodb 分组查询的相关文章

mongodb 分组查询统计去掉重复的记录

mongodb版本号是,MongoDB shell version: 2.4.4 操作环境,shell窗口 ,如下所示: [mongo_user@mongodb_dbs ~]# mongo --port 30100 MongoDB shell version: 2.4.4 connecting to: 127.0.0.1:30000/test mongos> mongos> use pos switched to db pos mongos> 1,先统计分组记录数,以paymentOrd

MongoDB分组查询,聚合查询,以及复杂查询

准备数据 from pymongo import MongoClient import datetime client=MongoClient('mongodb://localhost:27017') table=client['db1']['emp'] l=[ ('张飞','male',18,'20170301','',7300.33,401,1), #以下是教学部 ('张云','male',78,'20150302','teacher',1000000.31,401,1), ('刘备','m

Mongodb 分组查询例子

db.tblCard.aggregate([     {         $match: {             "sNo": {                 "$exists": true             },             "pNo": {                 "$exists": true             },             "pEffDate"

mongodb 分组聚合查询

MongoDB,分组,聚合 使用聚合,db.集合名.aggregate- 而不是find 管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数.MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理.管道操作是可以重复的. 每一个操作符(集合)都会接受一连串的文档,对这些文档做一些类型转换,最后将转换后的文档作为结果传递给下一个操作符,对于最后一个操作符,是将结果返回给客户端 //分组(这里制定了分组字段 $+字段名)//这里可以理解为

Mongodb for C# 分组查询

#region 排序获取集合 static List<BsonDocument> GetPagerWithGroup(string connectionString, string databaseName, string collectionName, IMongoQuery param, GroupByBuilder groupByBuilder, PageInfo info, out int pageCount) /// <summary> ///分组查询获取集合 /// &

5 功能4:个人站点页面设计(ORM跨表与分组查询)

1.个人站点页面文章的查询 # 个人站点 http://www.cnblogs.com/wh1520577322/ http://www.cnblogs.com/liucong12345/ http://www.cnblogs.com/kin1492/ (1)用户未找到,404页面构建 url # 个人站点页面设计 re_path(r'^(?P<username>\w+)$', views.home_site, name='home_site'), view 404.html <!DOC

BBS--功能4:个人站点页面设计(ORM跨表与分组查询)

查询: 日期归档查询 1 date_format ============date,time,datetime=========== create table t_mul_new(d date,t time,dt datetime); insert into t_mul_new values(now(),now(),now()); select * from t_mul; mysql> select * from t_mul; +------------+----------+---------

MongoDB高级查询用法

译 MongoDB高级查询用法 2018年09月04日 18:52:43 小小小辉happy 阅读数 752更多 分类专栏: 数据库 db的帮助文档 输入:db.help(); db.AddUser(username,password[, readOnly=false])  添加用户 db.auth(usrename,password)     设置数据库连接验证 db.cloneDataBase(fromhost)     从目标服务器克隆一个数据库 db.commandHelp(name)

SQL group 分组查询

1.使用group by进行分组查询  在使用group by关键字时,在select列表中可以指定的项目是有限制的,select语句中仅许以下几项:  被分组的列 为每个分组返回一个值得表达式,例如用一个列名作为参数的聚合函数group by的使用在这只写几个例子吧:例: select courseID,avg(score) as 课程平均成绩 from score group by courseID 例: select studentID as 学员编号,courseID as 内部测试,a