MySQL5.6的Linux安装shell脚本之二进制安装

最近在写一个MySQL的shell安装脚本 说明一点着里面的所有路径都是绝对路径 下面来总结一下安装 遇到的一些问题,以及安装的过程


这个是自带的安装过程

shell>groupadd mysql
shell>useradd -r -g mysql mysql
shell>cd /usr/local
shell>tar zxvf /path/to/mysql-VERSION-OS.tar.gz
shell>ln -s full-path-to-mysql-VERSION-OS mysql
shell>cd mysql
shell>chown -R mysql .
shell>chgrp -R mysql .
shell>scripts/mysql_install_db --user=mysql
shell>chown -R root .
shell>chown -R mysql data
shell>bin/mysqld_safe --user=mysql &
# Next command is optional
shell>cp support-files/mysql.server /etc/init.d/mysql.server

安装之前首先检查有没有mysql的进程,如果有我们还安装个啥

mysqlProcessNum=/bin/ps aux | /bin/grep mysql | /usr/bin/wc -l | /bin/awk <span style="color: #800000;">'</span><span style="color: #800000;">{ print $1 }</span><span style="color: #800000;">'</span><span style="color: #000000;">;
if [ $mysqlProcessNum -gt 3 ]; then
    echo “已经安装MySQL“
    exit
fi

然后下载(可以从官网下载,但是个人感觉太慢了,于是就搭建了一个简单的ftp服务器,当然也可以本地上传嘛,在这里我就不细说了)

# download mysql package
yum install libaio   #MySQL的一个依赖包
/usr/bin/yum install awk wget -y
mysqlDownloadURL=ftp://。。。。。。。。。/pub/mysql/mysql-5.6.25-linux-glibc2.5-x86_64.tar.gz;
cd /tmp;
/bin/rm -rf mysql*.tar.gz
/usr/bin/wget $mysqlDownloadURL;

好我们已经下载好了

下面开始进入正题

解压,建立软连接

packageName=`/bin/ls | /bin/grep mysql*.tar.gz`;
# unpakcage mysql
/bin/tar zxvf $packageName -C /usr/local
mysqlAllNameDir=`/bin/ls -l /usr/local | grep mysql | /bin/awk '{ print $9 }'`
/bin/ln -s $mysqlAllNameDir /usr/local/mysql

添加用户和用户组(判断一下,如果没添加就添加一下)

userNum=`/bin/cat /etc/passwd | /bin/grep mysql | /bin/awk -F ':' '{ print $1 }' | /usr/bin/wc -l`
if [ $userNum -lt 1 ];then
    /usr/sbin/groupadd mysql
    /usr/sbin/useradd -d /usr/local/mysql -s /sbin/nologin -g mysql mysql
    echo "成功添加"
fi

检查/etc下面是否有my.cnf文件,有的话就干掉,或者备份

/bin/mv /etc/my.cnf /etc/my.cnf.bak

下面初始化

```/usr/local/mysql/scripts/mysql_install_db —datadir=/usr/local/mysql/data —user=mysql —basedir=/usr/local/mysql


说明一点!!!修改权限一定要在初始化之后,否则初始化之后的data目录不一定被附有权限


```shell
/bin/chown -R root.mysql /usr/local/mysql

/bin/chown -R mysql.mysql /usr/local/mysql/data/

现在可以自己写一个配置文件放在 /etc 下面

/etc/my.cnf (这里也说明一点,MySQL配置文件有参数替换原则)

顺序是这样的

[client]
socket=/usr/local/mysql/mysql-files/mysql.sock
[mysqld]
explicit_defaults_for_timestamp=true
datadir=/usr/local/mysql/data
socket=/usr/local/mysql/mysql-files/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# LOG
slow_query_log = 1
slow_query_log_file = /usr/local/mysql/mysql-files/mysql-slow.log
long_query_time = 2
# GENERAL LOG
#general_log = 1
#general_log_file = /usr/local/mysql/mysql-files/mysql-general.log
# BINARY LOG
server_id=101
log_bin=/usr/local/mysql/mysql-files/mysql-bin.log
binlog_format=ROW
sync_binlog=1
expire_logs_days=7
# ERROR LOG
log_error=/usr/local/mysql/mysql-files/mysql.err

# OTHER
character_set_server = utf8mb4
transaction-isolation = READ-COMMITTED
max_connections = 1000
log-queries-not-using-indexes
log_throttle_queries_not_using_indexes = 10

# INNODB
innodb_strict_mode=1
innodb_file_format=Barracuda
innodb_file_format_max=Barracuda
innodb_read_io_threads=4
innodb_write_io_threads=8 # 8 ~ 12
innodb_io_capacity=1000 # HDD:800 ~ 1200 SSD: 10000+
innodb_adaptive_flushing=1 # SSD: 0
innodb_flush_log_at_trx_commit=1
innodb_max_dirty_pages_pct=75
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1
innodb_flush_neighbors=1 # SSD:0
innodb_log_file_size=1024M # SSD:4G~8G HDD:1G~2G
innodb_purge_threads=1 # SSD:4
innodb_lock_wait_timeout=3
innodb_print_all_deadlocks=1
pid-file=/usr/local/mysql/data/mysqld/mysqld.pid

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/usr/local/mysql/data/mysqld/mysqld.pid

下面以mysql_safe方式启动

/usr/local/mysql/bin/mysqld_safe &

好下面启动mysqld

/usr/local/mysql/bin/mysqld restart

[root@db mysql]# ./bin/mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.25-log MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.

mysql> show databases;
+——————————+
| Database           |
+——————————+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+——————————+
4 rows in set (0.00 sec)

mysql>

 

说明几点:  

 

 

其他要说明的我在之前的安装过程中已经说明了

下面就是安装脚本的基本过程

#!/bin/bash
# mysql install script, the home directory is /usr/local/mysql-VERSION and the soft link is /usr/local/mysql
yum install libaio
/usr/bin/yum install awk wget -y
config=`/bin/pwd`
mysqlProcessNum=`/bin/ps aux | /bin/grep mysql | /usr/bin/wc -l | /bin/awk '{ print $1 }'`;
if [ $mysqlProcessNum -gt 3 ]; then
    echo "已经安装MySQL"
fi

# download mysql package
mysqlDownloadURL=ftp://。。。。。。。/pub/mysql/mysql-5.6.25-linux-glibc2.5-x86_64.tar.gz;
cd /tmp;
/bin/rm -rf mysql*.tar.gz
/usr/bin/wget $mysqlDownloadURL;
packageName=`/bin/ls | /bin/grep mysql*.tar.gz`;
# unpakcage mysql
/bin/tar zxvf $packageName -C /usr/local
mysqlAllNameDir=`/bin/ls -l /usr/local | grep mysql | /bin/awk '{ print $9 }'`
/bin/ln -s $mysqlAllNameDir /usr/local/mysql
userNum=`/bin/cat /etc/passwd | /bin/grep mysql | /bin/awk -F ':' '{ print $1 }' | /usr/bin/wc -l`
if [ $userNum -lt 1 ];then
    /usr/sbin/groupadd mysql
    /usr/sbin/useradd -d /usr/local/mysql -s /sbin/nologin -g mysql mysql
    echo "成功添加"
fi
#/bin/mv /etc/my.cnf /etc/my.cnf.bak
/usr/local/mysql/scripts/mysql_install_db --datadir=/usr/local/mysql/data --user=mysql --basedir=/usr/local/mysql
/bin/chown -R root.mysql /usr/local/mysql
/bin/chown -R mysql.mysql /usr/local/mysql/data/
#我的配置文件放到root目录下面了

/bin/cp $config/my.cnf /etc/    

/usr/local/mysql/bin/mysqld_safe &
#/bin/chown -R mysql.mysql /usr/local/mysql/data/#/bin/cp $config/my.cnf /etc/
#cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
#chmod 755 /etc/init.d/mysqld


搭建简单FTP服务器以及遇到的几个问题(一)

FTP 是 File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于 Internet 上的控制文件的双向传输。同时,它也是一个应用程序(Application)。

FTP的服务器软件有很多下面就拿 vsftpd 举例。 vsftpd 是一款在Linux发行版本里面最主流的FTP服务器程序,特点是小巧轻快,安全易用


下面开始安装

先检测是否存在vsftp服务

[root@tomcat ~]# rpm -qa |grep vsftpd

没有,下面开始安装

[root@tomcat ~]# yum install vsftpd* -y

使用vsftpd软件,主要包括如下几个命令:

[root@tomcat ~]# /etc/init.d/vsftpd restart
Shutting down vsftpd:                                      [  OK  ]
Starting vsftpd for vsftpd:                                [  OK  ]

访问:失败

错误排查:防火墙没关闭

[root@tomcat ~]# /etc/init.d/iptables stop
iptables: Setting chains to policy ACCEPT: filter          [  OK  ]
iptables: Flushing firewall rules:                         [  OK  ]
iptables: Unloading modules:                               [  OK  ]
[root@tomcat ~]#

连上(但是是秘名用户就能访问)

下面我们开始更改一下配置文件

[root@tomcat ~]# vi /etc/vsftpd/vsftpd.conf

##配置文件的内容简单介绍一下:

# Example config file /etc/vsftpd/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=NO      //禁止匿名用户访问
#
# Uncomment this to allow local users to log in.
local_enable=YES    //允许本地用户登录FTP
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES    //运行用户在FTP目录中有写入的权限
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022    //设置本地用户的文件生成掩码为022,默认为077
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES    
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES    //激活目录信息,当远程用户更改目录时,将出现提示信息
#
# The target log file can be vsftpd_log_file or xferlog_file.
# This depends on setting xferlog_std_format parameter
xferlog_enable=YES    //启用上传和下载日志功能
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES    //启用FTP数据端口的连接请求
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# The name of log file when xferlog_enable=YES and xferlog_std_format=YES
# WARNING - changing this filename affects /etc/logrotate.d/vsftpd.log
#xferlog_file=/var/log/xferlog
#
# Switches between logging into vsftpd_log_file and xferlog_file files.
# NO writes to vsftpd_log_file, YES to xferlog_file
xferlog_std_format=YES    //是否使用标准的日志文件格式
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd/banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=YES    //让vsftpd处于独立启动监听端口模式
#
# This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6
# sockets, you must run two copies of vsftpd with two configuration files.
# Make sure, that one of the listen options is commented !!
#listen_ipv6=YES

pam_service_name=vsftpd    //设置PAM认证服务配置文件名称,文件存放在/etc/pam.d/目录
userlist_enable=YES    //用户列表中的用户是否允许登录FTP服务器
tcp_wrappers=YES    //使用tcp_wrappwers作为主机访问控制方式

下面我设置成禁止用户访问模式

然后定义一个用户名

[root@tomcat ~]# useradd test
[root@tomcat ~]# passwd test
Changing password for user test.
New password: 
BAD PASSWORD: it is WAY too short
BAD PASSWORD: is too simple
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@tomcat ~]# 

密码设置为123

然后访问一下:

但是访问不进去:

百度了一下才知道是 selinux的问题

[root@tomcat ~]# vi /etc/selinux/config

重启一下

[root@tomcat ~]# reboot 

Broadcast message from root@tomcat.56team.com
    (/dev/pts/0) at 18:42 ...

The system is going down for reboot NOW!
[root@tomcat ~]# 

查看是否关闭了

[root@tomcat ~]# sestatus
SELinux status:                 disabled
[root@tomcat ~]#

最简单的FTP服务器就搭建好了



Shell编程之 bash 引号

突然发现bash是一个很有意思的东西,对于空格,单引号,双引号,反引号都有特殊的含义,而且在空格的方式来看还有很多说法 下面我就这几天遇到的问题来逐一总结一下常见的知识:(其中单引号和双引号直接的对比比较明显,反引号可能在书写方面和单引号比较像)


我们先说这三个引号

#反引号:

[root@iZ28b4rx8dxZ mysql_shell]# echo `date +%Y%m%d`
20161106

  或者

[root@iZ28b4rx8dxZ mysql_shell]# echo "the date is `date +%Y%m%d`"
the date is 20161106

  以上的说明也就是把date解释成一个命令输出结果

#单引号:

[root@iZ28b4rx8dxZ ~]# echo '$PWD'
$PWD

  但是要用单引号打印出来的内容里面有单引号呢:会出现如下的状况:(也就是说bash会认为输入的单引号还没有结束)

[root@iZ28b4rx8dxZ ~]# echo 'The answer isn't right'
> 
> '
The answer isnt right

  解决方法是有的:

$’str’ 之间到反斜杠都将转义字符来实现,百度看了看这个方法是bash特有的方法

[root@iZ28b4rx8dxZ ~]#  echo $'The answer isn\'t right'
The answer isn't right

双引号

我们可以和上面的单引号对比,$ 发生变量的引用, 而在单引号中的$, 就是它的字面意思

[root@iZ28b4rx8dxZ ~]# echo "$PWD"
/root

另外反斜杠\单独说一下,反斜杠是一个转义字符,但是如果在单引号中的话就是一个普通的字符

[root@iZ28b4rx8dxZ ~]# echo "He said, \"this is mine\""
He said, "this is mine"
  [root@iZ28b4rx8dxZ ~]# echo 'He said, \"this is mine\"'
  He said, \"this is mine\"

其他的特殊字符都是同理

#注意!!!!!!!!

反引号和单引号很像,所以切勿弄混

而当你需要得到一个命令的输出时,请使用反引号;当你需要输出的是一个字符串时,请使用单引号



Python简单脚本之一 (备份压缩文件)

主要实现的功能如下:


首先我要建立一备份的目录 ,我需要先判断有没有这个目录

import time
import os
d_dir='/usr/local/py/backup/'    #备份目标目录
d_files='system_back.tar.gz'    #命名文件
s_dir =['/etc/','/usr/local/mongodb/']    #源目录
data=time.strftime('%Y%m%d')    #时间
if os.path.exists(d_dir) == False:
        os.mkdir(d_dir)
        print ('Successfully create dir!')
else:
        print ('the dir {0} is exists !'.format(d_dir))

效果如下

下面我来处理备份文件的名字:

我想加一个时间的目录 把备份信息放在时间的目录下面

然后我需要判断这个时间的目录是否存在并且打印信息

import time
import os
d_dir='/usr/local/py/backup/'    
d_files='system_back.tar.gz'    #命名文件

s_dir =['/etc/','/usr/local/mongodb/']    #源目录
data=time.strftime('%Y%m%d')    #时间

d_dir1 = d_dir + data + '/'        #备份目标目录

if os.path.exists(d_dir1) == False:
        os.makedirs(d_dir1)
        print ('Successfully create {0}!'.format(d_dir1))
else:
        print ('the dir {0} is exists !'.format(d_dir1))

效果:

接下来我们就能够进行简单的备份了:

import time
import os
d_dir='/usr/local/py/backup/'    #备份目标目录
d_files='system_back.tar.gz'    #命名文件

s_dir =['/etc/','/usr/local/mongodb/']    #源目录
data=time.strftime('%Y%m%d')    #时间
d_dir1 = d_dir + data + '/'        #创建时间的目录
r_name = d_dir1 + d_files        #压缩文件所在的目录以及名字

if os.path.exists(d_dir1) == False:
        os.makedirs(d_dir1)
        print ('Successfully create {0}!'.format(d_dir1))
else:
        print ('the dir {0} is exists !'.format(d_dir1))

tar_dir = 'tar -czvf {0} {1} '.format(r_name,' '.join(s_dir))    #定义备份文件
if os.system(tar_dir) == 0:        #执行备份的命令
    print ('the backup files is successfully!')
else :
    print ('the backup files is falsed!')

效果:

现在我们来优化一下这个脚本:

```python

#!/usr/bin python #! backup system files import time import os import sys d_dir=’/usr/local/py/backup/’ #备份目标目录 d_files=’system_back.tar.gz’ #命名文件

s_dir =[‘/etc/’,’/usr/local/mongodb/’] #源目录 data=time.strftime(‘%Y%m%d’) #时间 d_dir1 = d_dir + data + ‘/’ #创建时间的目录 r_name = d_dir1 + d_files #压缩文件所在的目录以及名字

def all_bak(): #写到函数里面 print (‘backup scripts start,please wait …’) print (‘\033[32m——————————————–\033[0m’) time.sleep(2) #等待两秒

if os.path.exists(d_dir1) == False:
        os.makedirs(d_dir1)
        print ('Successfully create {0}!'.format(d_dir1))
else:
        print ('the dir {0} is exists !'.format(d_dir1))

tar_dir = 'tar -czvf {0} {1} '.format(r_name,' '.join(s_dir))    #定义备份文件
if os.system(tar_dir) == 0:        #执行备份的命令
    print ('the backup files {0} is successfully!').format(r_name)        #打印出来备份的目录
else :
    print ('the backup files is falsed!') try:                                #不输入参数的时候处理异常
if len(sys.argv[1]) == 0:
    pass except IndexError:
    print ('warning:{please exec {0} help|all_bak}'.format(sys.argv[0])) try:                                 #输入参数的时候处理异常
if sys.argv[1] == 'all_bak':
    all_bak()                    #输入参数为all_bak的时候执行备份
else:
    print ('warning:{please exec {0} help|all_bak}'.format(sys.argv[0]))     except IndexError:
pass
```

效果:



MySQL与Mongo简单的查询 (一)

相信很多数据库方向的人都知道关系型数据库和菲关系型数据库的区别吧 在这里我就略微的点一下 关系型数据库,是指采用了关系模型来组织数据的数据库,由二维表及其之间的联系所组成的一个数据组织。


但是再想想啊,虽然更方便,更易于维护,但是在海量数据的高并发与高效率的读写 等等 要求下,关系型数据库也就遇到了瓶颈,相对来说的一些标准也就限制了关系型数据库,于是逐渐诞生了一种

为 海量数据而生的 NoSQL 用于指代那些非关系型的,分布式的,且一般不保证遵循ACID原则的数据存储系统 。主要有 面向海量数据访问的文档型数据库,像 MongoDB 和 CouchDB 等,面向高性能并发读写的 key-value 数据库,代表有 Redis 和 Tokyo Cabinet 等,NOSQL 大多都是 面向可扩展性的分布式数据库,基本上都是基于 键值对的,类似于 json 格式的数据存储, 所以自然 不需要经过 SQL 层的解析,性能一遍都非常高。

为了更好地了解关系型数据库与菲关系型数据库的一些知识,我在 建表查询上面以 MySQLMongoDB 作为两种数据库的代表简单的介绍一下 ,下面说一下具体的要求:

我想查询的内容是这样的:

分数大于0且人名是bob或是jake的总分数   平均分数   最小分数   最大分数   计数

 

举这个实例来试试用 MySQLmongodb 分别写一个查询

首先我们先做一些准备工作

建立MySQL的数据库表结构如下

CREATE TABLE `new_schema`.`demo` (
   `id` INT NOT NULL,
   `person` VARCHAR(45) NOT NULL,
   `score` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`));

建完表之后我们来插入一些数据

INSERT INTO `new_schema`.`demo` (`id`, `person`, `score`) VALUES ('1', 'bob', '50');
INSERT INTO `new_schema`.`demo` (`id`, `person`, `score`) VALUES ('2', 'jake', '60');
INSERT INTO `new_schema`.`demo` (`id`, `person`, `score`) VALUES ('3', 'bob', '100');
INSERT INTO `new_schema`.`demo` (`id`, `person`, `score`) VALUES ('6', 'jake', '100');
INSERT INTO `new_schema`.`demo` (`id`, `person`, `score`) VALUES ('8', 'li', '100');

我截个图方便看一下结构

 

好      接下来我们进入 mongodb 的准备工作

看一下建立的mongodb的集合里面文档的结构(基本跟MySQL一毛一样)在这里我就不写插入文档的具体过程了 (为了便看mongodb的显示我都用两种格式显示:一个是表格模块显示   一个是文本模块显示)

 

这个是表格模块显示

 

 

这个是文本模块显示

 

/* 1 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e17"),
    "person" : "bob",
    "sorce" : 50
}

/* 2 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e18"),
    "person" : "bob",
    "sorce" : 100
}

/* 3 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e19"),
    "person" : "jake",
    "sorce" : 60
}

/* 4 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e1a"),
    "person" : "jake",
    "sorce" : 100
}

/* 5 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e1b"),
    "person" : "li",
    "sorce" : 100
}

 


##开始进入正题

现在我想查的MySQL语句是这样的(分数大于0且人名是bob或是jake的总分数   平均分数   最小分数   最大分数   计数)

SELECT person, SUM(score), AVG(score), MIN(score), MAX(score), COUNT(*) 
    FROM demo 
        WHERE score > 0 AND person IN('bob','jake') 
            GROUP BY person;

下面开始用Mongo写出这个查询

  首先想到的是聚合框架

db.demo.aggregate(
{
    "$match":{
        "$and":[
            {"sorce":{"$gt":0}},
            {"person":{"$in":["bob","jake"]}}
            ]
        }
    }

得到这个结果

 

这个是表格模块显示的结果:

 

 

这个是文本模块显示的结果:

 

/* 1 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e17"),
    "person" : "bob",
    "sorce" : 50
}

/* 2 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e18"),
    "person" : "bob",
    "sorce" : 100
}

/* 3 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e19"),
    "person" : "jake",
    "sorce" : 60
}

/* 4 */
{
    "_id" : ObjectId("58043fa8e9a7804c05031e1a"),
    "person" : "jake",
    "sorce" : 100
}

然后想要分组并且显示最大 最小 总计 平均值 和计数值

db.demo.aggregate(
{
    "$match":{
        "$and":[
            {"sorce":{"$gt":0}},
            {"person":{"$in":["bob","jake"]}}
            ]
        }
    },
{
   "$group":{"_id":"$person",
       "sumSorce":{"$sum":"$sorce"},
       "avgSorce":{"$avg":"$sorce"},
       "lowsetSorce":{"$min":"$sorce"},
       "highestSorce":{"$max":"$sorce"},
       "count":{"$sum":1}} 
    }
)

得到的结果就是     分数大于0且人名是bob或是jake的总分数   平均分数   最小分数   最大分数   计数

 

结果的表格模块显示:

 

 

 

结果的文本模块显示:

 

/* 1 */
{
    "_id" : "bob",
    "sumSorce" : 150,
    "avgSorce" : 75.0,
    "lowsetSorce" : 50,
    "highestSorce" : 100,
    "count" : 2.0
}

/* 2 */
{
    "_id" : "jake",
    "sumSorce" : 160,
    "avgSorce" : 80.0,
    "lowsetSorce" : 60,
    "highestSorce" : 100,
    "count" : 2.0
}

以上就是一个简单查询的例子



Pagination