聽(tīng)說(shuō)項(xiàng)目里面Aggregation用的多,那就專門(mén)針對(duì)這個(gè)多多練習(xí)一下。
基本的操作包括:
•$project - 可以從子文檔中提取字段,可以重命名字段
•$match - 可以實(shí)現(xiàn)查找的功能
•$limit - 接受一個(gè)數(shù)字n,返回結(jié)果集中的前n個(gè)文檔。
•$skip - 接受一個(gè)數(shù)字n,丟棄結(jié)果集中的前n個(gè)文檔。效率比較低,依然會(huì)遍歷前n個(gè)文檔。
•$unwind - 可以將一個(gè)包含數(shù)組的文檔切分成多個(gè), 比如你的文檔有 中有個(gè)數(shù)組字段 A, A中有10個(gè)元素, 那么經(jīng)過(guò) $unwind處理后會(huì)產(chǎn)生10個(gè)文檔,這些文檔只有 字段 A不同
•$group - 統(tǒng)計(jì)操作, 還提供了一系列子命令
–$avg, $sum …
•$sort - 排序
Python篇
實(shí)驗(yàn)一、學(xué)生數(shù)據(jù)統(tǒng)計(jì)
1、生成學(xué)生數(shù)據(jù):
#!/usr/bin/env python
# coding=utf-8
from pymongo import MongoClient
from random import randint
name1 = ["yang ", "li ", "zhou "]
name2 = [
"chao",
"hao",
"gao",
"qi gao",
"hao hao",
"gao gao",
"chao hao",
"ji gao",
"ji hao",
"li gao",
"li hao",
]
provinces = [
"guang dong",
"guang xi",
"shan dong",
"shan xi",
"he nan"
]
client = MongoClient('localhost', 27017)
db = client.student
sm = db.smessage
sm.remove()
for i in range(1, 100):
name = name1[randint(0, 2)] + name2[randint(0, 10)]
province = provinces[randint(0, 4)]
new_student = {
"name": name,
"age": randint(1, 30),
"province": province,
"subject": [
{"name": "chinese", "score": randint(0, 100)},
{"name": "math", "score": randint(0, 100)},
{"name": "english", "score": randint(0, 100)},
{"name": "chemic", "score": randint(0, 100)},
]}
print new_student
sm.insert_one(new_student)
print sm.count()
好了,現(xiàn)在數(shù)據(jù)庫(kù)里面有100條學(xué)生數(shù)據(jù)了。
現(xiàn)在我要得到廣東學(xué)生的平均年齡,在mongo控制臺(tái)輸入:
如果想到得到所有省份的平均年齡,那就更加簡(jiǎn)單了:
db.smessage.aggregate(
{$match: {province: "guang dong"}}
)
{ "_id" : "guang xi", "age" : 15.19047619047619 }
{ "_id" : "guang dong", "age" : 16.05263157894737 }
{ "_id" : "shan dong", "age" : 17.44 }
{ "_id" : "he nan", "age" : 20 }
{ "_id" : "shan xi", "age" : 16.41176470588235 }
如果想得到廣東省所有科目的平均成績(jī):
db.smessage.aggregate(
{$match: {province: "guang dong"}},
{$unwind: "$subject"},
{$group: { _id: {province:"$province",sujname:"$subject.name"}, per:{$avg:"$subject.score"}}}
)
加上排序:
db.smessage.aggregate(
{$match: {province: "guang dong"}},
{$unwind: "$subject"},
{$group: { _id: {province:"$province",sujname:"$subject.name"}, per:{$avg:"$subject.score"}}},
{$sort:{per:1}}
)
實(shí)驗(yàn)二、尋找發(fā)帖水王
有一個(gè)保存著雜志文章的集合,你可能希望找出發(fā)表文章最多的那個(gè)作者。假設(shè)每篇文章被保存為MongoDB中的一個(gè)文檔。
1、插入數(shù)據(jù)
#!/usr/bin/env python
# coding=utf-8
from pymongo import MongoClient
from random import randint
name = [
'yangx',
'yxxx',
'laok',
'kkk',
'ji',
'gaoxiao',
'laoj',
'meimei',
'jj',
'manwang',
]
title = [
'123',
'321',
'12',
'21',
'aaa',
'bbb',
'ccc',
'sss',
'aaaa',
'cccc',
]
client = MongoClient('localhost', 30999)
db = client.test
bbs = db.bbs
bbs.remove()
for i in range(1, 10000):
na = name[randint(0, 9)]
ti = title[randint(0, 9)]
newcard = {
'author': na,
'title': ti,
}
bbs.insert_one(newcard)
print bbs.count()
現(xiàn)在我們擁有了10000條文章數(shù)據(jù)了。
2、用$project將author字段投射出來(lái)
{"$project": {"author":1}}
這個(gè)語(yǔ)法與查詢中的字段選擇器比較像:可以通過(guò)指定"fieldname" : 1選擇需要投射的字段,或者通過(guò)指定"fieldname":0排除不需要的字段。
執(zhí)行完這個(gè)"$project"操作之后,結(jié)果集中的每個(gè)文檔都會(huì)以{"_id" : id, "author" : "authorName"}這樣的形式表示。這些結(jié)果只會(huì)在內(nèi)存中存在,不會(huì)被寫(xiě)入磁盤(pán)。
3、用group將作者名稱分組
{"group":{"_id":"$author","count":{"$sum":1}}}
這樣就會(huì)將作者按照名字排序,某個(gè)作者的名字每出現(xiàn)一次,就會(huì)對(duì)這個(gè)作者的"count"加1。
這里首先指定了需要進(jìn)行分組的字段"author"。這是由"_id" : "$author"指定的。可以將這個(gè)操作想象為:這個(gè)操作執(zhí)行完后,每個(gè)作者只對(duì)應(yīng)一個(gè)結(jié)果文檔,所以"author"就成了文檔的唯一標(biāo)識(shí)符("_id")。
第二個(gè)字段的意思是為分組內(nèi)每個(gè)文檔的"count"字段加1。注意,新加入的文檔中并不會(huì)有"count"字段;這"$group"創(chuàng)建的一個(gè)新字段。
執(zhí)行完這一步之后,結(jié)果集中的每個(gè)文檔會(huì)是這樣的結(jié)構(gòu):{"_id" : "authorName", "count" : articleCount}。
4、用sort排序
{"$sort" : {"count" : -1}}
這個(gè)操作會(huì)對(duì)結(jié)果集中的文檔根據(jù)"count"字段進(jìn)行降序排列。
5、限制結(jié)果為前5個(gè)文檔
這個(gè)操作將最終的返回結(jié)果限制為當(dāng)前結(jié)果中的前5個(gè)文檔。
在MongoDB中實(shí)際運(yùn)行時(shí),要將這些操作分別傳給aggregate()函數(shù):
> db.articles.aggregate({"$project" : {"author" : 1}},
... {"$group" : {"_id" : "$author", "count" : {"$sum" : 1}}},
... {"$sort" : {"count" : -1}},
... {"$limit" : 5}
... )
aggregate()會(huì)返回一個(gè)文檔數(shù)組,其中的內(nèi)容是發(fā)表文章最多的5個(gè)作者。
{ "_id" : "yangx", "count" : 1028 }
{ "_id" : "laok", "count" : 1027 }
{ "_id" : "kkk", "count" : 1012 }
{ "_id" : "yxxx", "count" : 1010 }
{ "_id" : "ji", "count" : 1007 }
Java篇
我在db中造了些數(shù)據(jù)(數(shù)據(jù)時(shí)隨機(jī)生成的, 能用即可),沒(méi)有建索引,文檔結(jié)構(gòu)如下:
Document結(jié)構(gòu):
{
"_id" : ObjectId("509944545"),
"province" : "海南",
"age" : 21,
"subjects" : [
{
"name":"語(yǔ)文",
"score" : 53
},
{
"name":"數(shù)學(xué)",
"score" : 27
},
{
"name":"英語(yǔ)",
"score" : 35
}
],
"name" : "劉雨"
}
接下來(lái)要實(shí)現(xiàn)兩個(gè)功能:
- 統(tǒng)計(jì)上海學(xué)生平均年齡
- 統(tǒng)計(jì)每個(gè)省各科平均成績(jī)
接下來(lái)一一道來(lái)
統(tǒng)計(jì)上海學(xué)生平均年齡
從這個(gè)需求來(lái)講,要實(shí)現(xiàn)功能要有幾個(gè)步驟: 1. 找出上海的學(xué)生. 2. 統(tǒng)計(jì)平均年齡 (當(dāng)然也可以先算出所有省份的平均值再找出上海的)。如此思路也就清晰了
首先上 $match, 取出上海學(xué)生
{$match:{'province':'上海'}}
接下來(lái) 用 $group 統(tǒng)計(jì)平均年齡
{$group:{_id:'$province',$avg:'$age'}}
$avg 是 $group的子命令,用于求平均值,類似的還有 $sum, $max ....
上面兩個(gè)命令等價(jià)于
select province, avg(age)
from student
where province = '上海'
group by province
下面是Java代碼
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("test");
DBCollection coll = db.getCollection("student");
/*創(chuàng)建 $match, 作用相當(dāng)于query*/
DBObject match = new BasicDBObject("$match", new BasicDBObject("province", "上海"));
/* Group操作*/
DBObject groupFields = new BasicDBObject("_id", "$province");
groupFields.put("AvgAge", new BasicDBObject("$avg", "$age"));
DBObject group = new BasicDBObject("$group", groupFields);
/* 查看Group結(jié)果 */
AggregationOutput output = coll.aggregate(match, group); // 執(zhí)行 aggregation命令
System.out.println(output.getCommandResult());
輸出結(jié)果:
{ "serverUsed" : "localhost/127.0.0.1:27017" ,
"result" : [
{ "_id" : "上海" , "AvgAge" : 32.09375}
] ,
"ok" : 1.0
}
如此工程就結(jié)束了,再看另外一個(gè)需求
統(tǒng)計(jì)每個(gè)省各科平均成績(jī)
首先更具數(shù)據(jù)庫(kù)文檔結(jié)構(gòu),subjects是數(shù)組形式,需要先‘劈'開(kāi),然后再進(jìn)行統(tǒng)計(jì)
主要處理步驟如下:
1. 先用$unwind 拆數(shù)組 2. 按照 province, subject 分租并求各科目平均分
$unwind 拆數(shù)組
按照 province, subject 分組,并求平均分
{$group:{
_id:{
subjname:”$subjects.name”, // 指定group字段之一 subjects.name, 并重命名為 subjname
province:'$province' // 指定group字段之一 province, 并重命名為 province(沒(méi)變)
},
AvgScore:{
$avg:”$subjects.score” // 對(duì) subjects.score 求平均
}
}
java代碼如下:
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("test");
DBCollection coll = db.getCollection("student");
/* 創(chuàng)建 $unwind 操作, 用于切分?jǐn)?shù)組*/
DBObject unwind = new BasicDBObject("$unwind", "$subjects");
/* Group操作*/
DBObject groupFields = new BasicDBObject("_id", new BasicDBObject("subjname", "$subjects.name").append("province", "$province"));
groupFields.put("AvgScore", new BasicDBObject("$avg", "$subjects.scores"));
DBObject group = new BasicDBObject("$group", groupFields);
/* 查看Group結(jié)果 */
AggregationOutput output = coll.aggregate(unwind, group); // 執(zhí)行 aggregation命令
System.out.println(output.getCommandResult());
輸出結(jié)果
{ "serverUsed" : "localhost/127.0.0.1:27017" ,
"result" : [
{ "_id" : { "subjname" : "英語(yǔ)" , "province" : "海南"} , "AvgScore" : 58.1} ,
{ "_id" : { "subjname" : "數(shù)學(xué)" , "province" : "海南"} , "AvgScore" : 60.485} ,
{ "_id" : { "subjname" : "語(yǔ)文" , "province" : "江西"} , "AvgScore" : 55.538} ,
{ "_id" : { "subjname" : "英語(yǔ)" , "province" : "上海"} , "AvgScore" : 57.65625} ,
{ "_id" : { "subjname" : "數(shù)學(xué)" , "province" : "廣東"} , "AvgScore" : 56.690} ,
{ "_id" : { "subjname" : "數(shù)學(xué)" , "province" : "上海"} , "AvgScore" : 55.671875} ,
{ "_id" : { "subjname" : "語(yǔ)文" , "province" : "上海"} , "AvgScore" : 56.734375} ,
{ "_id" : { "subjname" : "英語(yǔ)" , "province" : "云南"} , "AvgScore" : 55.7301 } ,
.
.
.
.
"ok" : 1.0
}
統(tǒng)計(jì)就此結(jié)束.... 稍等,似乎有點(diǎn)太粗糙了,雖然統(tǒng)計(jì)出來(lái)的,但是根本沒(méi)法看,同一個(gè)省份的科目都不在一起。囧
接下來(lái)進(jìn)行下加強(qiáng),
支線任務(wù): 將同一省份的科目成績(jī)統(tǒng)計(jì)到一起( 即,期望 'province':'xxxxx', avgscores:[ {'xxx':xxx}, ....] 這樣的形式)
要做的有一件事,在前面的統(tǒng)計(jì)結(jié)果的基礎(chǔ)上,先用 $project 將平均分和成績(jī)?nèi)嗟揭黄?,即形如下面的樣?/p>
{ "subjinfo" : { "subjname" : "英語(yǔ)" ,"AvgScores" : 58.1 } ,"province" : "海南" }
再按省份group,將各科目的平均分push到一塊,命令如下:
$project 重構(gòu)group結(jié)果
{$project:{province:"$_id.province", subjinfo:{"subjname":"$_id.subjname", "avgscore":"$AvgScore"}}
$使用 group 再次分組
{$group:{_id:"$province", avginfo:{$push:"$subjinfo"}}}
java 代碼如下:
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("test");
DBCollection coll = db.getCollection("student");
/* 創(chuàng)建 $unwind 操作, 用于切分?jǐn)?shù)組*/
DBObject unwind = new BasicDBObject("$unwind", "$subjects");
/* Group操作*/
DBObject groupFields = new BasicDBObject("_id", new BasicDBObject("subjname", "$subjects.name").append("province", "$province"));
groupFields.put("AvgScore", new BasicDBObject("$avg", "$subjects.scores"));
DBObject group = new BasicDBObject("$group", groupFields);
/* Reshape Group Result*/
DBObject projectFields = new BasicDBObject();
projectFields.put("province", "$_id.province");
projectFields.put("subjinfo", new BasicDBObject("subjname","$_id.subjname").append("avgscore", "$AvgScore"));
DBObject project = new BasicDBObject("$project", projectFields);
/* 將結(jié)果push到一起*/
DBObject groupAgainFields = new BasicDBObject("_id", "$province");
groupAgainFields.put("avginfo", new BasicDBObject("$push", "$subjinfo"));
DBObject reshapeGroup = new BasicDBObject("$group", groupAgainFields);
/* 查看Group結(jié)果 */
AggregationOutput output = coll.aggregate(unwind, group, project, reshapeGroup);
System.out.println(output.getCommandResult());
結(jié)果如下:
{ "serverUsed" : "localhost/127.0.0.1:27017" ,
"result" : [
{ "_id" : "遼寧" , "avginfo" : [ { "subjname" : "數(shù)學(xué)" , "avgscore" : 56.46666666666667} , { "subjname" : "英語(yǔ)" , "avgscore" : 52.093333333333334} , { "subjname" : "語(yǔ)文" , "avgscore" : 50.53333333333333}]} ,
{ "_id" : "四川" , "avginfo" : [ { "subjname" : "數(shù)學(xué)" , "avgscore" : 52.72727272727273} , { "subjname" : "英語(yǔ)" , "avgscore" : 55.90909090909091} , { "subjname" : "語(yǔ)文" , "avgscore" : 57.59090909090909}]} ,
{ "_id" : "重慶" , "avginfo" : [ { "subjname" : "語(yǔ)文" , "avgscore" : 56.077922077922075} , { "subjname" : "英語(yǔ)" , "avgscore" : 54.84415584415584} , { "subjname" : "數(shù)學(xué)" , "avgscore" : 55.33766233766234}]} ,
{ "_id" : "安徽" , "avginfo" : [ { "subjname" : "英語(yǔ)" , "avgscore" : 55.458333333333336} , { "subjname" : "數(shù)學(xué)" , "avgscore" : 54.47222222222222} , { "subjname" : "語(yǔ)文" , "avgscore" : 52.80555555555556}]}
.
.
.
] , "ok" : 1.0}
您可能感興趣的文章:- 基于Django統(tǒng)計(jì)博客文章閱讀量
- MongoDB 中聚合統(tǒng)計(jì)計(jì)算--$SUM表達(dá)式
- django項(xiàng)目用higcharts統(tǒng)計(jì)最近七天文章點(diǎn)擊量
- 使用django的ORM框架按月統(tǒng)計(jì)近一年內(nèi)的數(shù)據(jù)方法
- Golang 函數(shù)執(zhí)行時(shí)間統(tǒng)計(jì)裝飾器的一個(gè)實(shí)現(xiàn)詳解
- Vue自定義指令上報(bào)Google Analytics事件統(tǒng)計(jì)的方法
- Golang 統(tǒng)計(jì)字符串字?jǐn)?shù)的方法示例
- 利用Celery實(shí)現(xiàn)Django博客PV統(tǒng)計(jì)功能詳解
- Google 統(tǒng)計(jì)圖表(Flash)小插件
- go語(yǔ)言之給定英語(yǔ)文章統(tǒng)計(jì)單詞數(shù)量(go語(yǔ)言小練習(xí))