mongo-mapreduce测试(4)——avg
mongo-mapreduce測試(1)——count/sum/where條件
mongo-mapreduce測試(2)——列轉行與finalize函數
mongo-mapreduce測試(3)——group by having
mongo-mapreduce測試(4)——avg
mongo-mapreduce測試(5)——max/min
mongo-mapreduce測試(6)——綜合測試
mongo-mapreduce測試(7)——使用js存儲過程
mongo-mapreduce測試(8)——階段總結(1)
mongo-mapreduce測試(9)——python調用
mongo-mapreduce測試(10)——階段總結(2)
mongo-mapreduce測試(11)——跟蹤調試
測試mapreduce的avg聚合函數的實現,類似如下SQL:
select name, avg(dic)
from tianyc_test3
group by name;
1. 測試數據如下:
> db.tianyc_test3.find()
{ "_id" : ObjectId("51258e47ff13bc6383473137"), "name" : "xtt", "dic" : 1 }
{ "_id" : ObjectId("51258e49ff13bc6383473138"), "name" : "xtt", "dic" : 2 }
{ "_id" : ObjectId("51258e4bff13bc6383473139"), "name" : "xtt", "dic" : 3 }
{ "_id" : ObjectId("51258e4eff13bc638347313a"), "name" : "xtt", "dic" : 4 }
{ "_id" : ObjectId("51258e50ff13bc638347313b"), "name" : "xtt", "dic" : 5 }
{ "_id" : ObjectId("51258e5aff13bc638347313c"), "name" : "yct", "dic" : 1 }
{ "_id" : ObjectId("51258e5cff13bc638347313d"), "name" : "yct", "dic" : 2 }
{ "_id" : ObjectId("51258e62ff13bc638347313e"), "name" : "neu", "dic" : 1 }
{ "_id" : ObjectId("51258e64ff13bc638347313f"), "name" : "neu", "dic" : 2 }
{ "_id" : ObjectId("51258e65ff13bc6383473140"), "name" : "neu", "dic" : 3 }
{ "_id" : ObjectId("51258e68ff13bc6383473141"), "name" : "neu", "dic" : 4 }
2. 編寫map函數
> var m = function(){
... emit(this.name,{dic:this.dic});
... }
3. 編寫reduce函數
> var r = function (key,values) {
... var sum = 0;
... for (var i=0; i<values.length; i++) {
... sum += values[i].dic;
... }
... return {name:key, avg: sum/values.length};
... };
4. 執行mapreduce
> var res = db.runCommand({
... mapreduce:'tianyc_test3',
... map:m,
... reduce:r,
... out:'tianyc_mr_Result1'
... }
... )
5. 查詢結果
> db.tianyc_mr_Result1.find()
{ "_id" : "neu", "value" : { "name" : "neu", "avg" : 2.5 } }
{ "_id" : "xtt", "value" : { "name" : "xtt", "avg" : 3 } }
{ "_id" : "yct", "value" : { "name" : "yct", "avg" : 1.5 } }
>
總結
以上是生活随笔為你收集整理的mongo-mapreduce测试(4)——avg的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设置ios6中UIViewControl
- 下一篇: 数据结构--单链表