当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL与Mongo简单的查询实例代码

MySQL与Mongo简单的查询实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

首先在这里我就不说关系型数据库与非关系型数据库之间的区别了(百度上有很多)直接切入主题

我想查询的内容是这样的:分数大于0且人名是bob或是jake的总分数 平均分数 最小分数 最大分数 计数

举这个实例来试试用mysql和mongodb分别写一个查询

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

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写出这个查询

  首先想到的是聚合框架

先用$match过滤 分数大于0且人名是bob或是jake

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
}

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

那么$group派上用场了:

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
}

以上所述是小编给大家介绍的mysql与mongo简单的查询实例代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网