mogodb聚合查询

版权声明:转发请注明,谢谢配合 https://blog.csdn.net/qq_31289187/article/details/82014801

例:统计查询总成绩排名前五的学生信息,学号、姓名、年龄、电话号码、英文成绩、数学成绩,总成绩

mysql中进行数据统计

select student_id,NAME,age,phoneno,english_score,math_score,sum(ifnull(english_score,0)+ifnull(math_score,0)) as total_score 
from student 
where sex = '男' group by student_id order by total_score desc limit 5;

查看:mogodb聚合函数使用手册

使用mogodb实现mysql相同的统计,主要是mogodb中聚合函数的使用,mogodb的语法很头疼,不容易查看!!!

db.getCollection('student-collection').aggregate(
[
 {
    $MATCH:
    {
        sex : "男"
    }
  }
  ,
  {
    $project:
    {  
        student_id:1, 
        NAME:1,
        age:1,
        phoneno:1,
        english_score:1,
        math_score:1,
        total_score:{$ADD:[{$IFNULL:["$english_score",0]},{$IFNULL:["$math_score",0]}]}
    }
 }
 ,
 {
   $sort:
   {
       total_score:-1
   }
 }
 ,
 {
    $LIMIT:5
 }
])

猜你喜欢

转载自blog.csdn.net/qq_31289187/article/details/82014801