MongoDB三種聚合命令用法介紹

chenfeng發表於2018-07-19

聚合(Aggregation)為集合文件資料提供了各種資料處理方法,並返回計算結果。

MongoDB提供了三種方法來執行聚合命令,分別為:聚合管道法,map-reduce法和單一目標聚合法

1.聚合管道法:

管道聚合方法可以理解為合計流水線法,就是把集合裡若干含數值型的文件記錄其鍵對應的值進行各種分類統計,有點類似於SQL語言裡的group by。

語法如下:

db.collection.agrregate(

[$match:{<field>}},

                  {$group:{<field1>,<field2>}}

  ]

說明:

field1為分類欄位;field2為含各種統計運算子的數值型欄位,比如$sum, $avg, $min,$max等運算子


>use test

> db.test.insert(

... [{id:"001",amount:2,price:15.2,ok:true},

... {id:"001",amount:3,price:14.8,ok:true},

... {id:"002",amount:4,price:40,ok:true},

... {id:"002",amount:2,price:10,ok:true},

... {id:"003",amount:3,price:20.3,ok:true}

... ]

... )

BulkWriteResult({

        "writeErrors" : [ ],

        "writeConcernErrors" : [ ],

        "nInserted" : 5,

        "nUpserted" : 0,

        "nMatched" : 0,

        "nModified" : 0,

        "nRemoved" : 0,

        "upserted" : [ ]

})



> db.test.aggregate({ $match:{ok:true}})

{ "_id" : ObjectId("5b50388dff7043cec86841af"), "id" : "001", "amount" : 2, "price" : 15.2, "ok" : true }

{ "_id" : ObjectId("5b50388dff7043cec86841b0"), "id" : "001", "amount" : 3, "price" : 14.8, "ok" : true }

{ "_id" : ObjectId("5b50388dff7043cec86841b1"), "id" : "002", "amount" : 4, "price" : 40, "ok" : true }

{ "_id" : ObjectId("5b50388dff7043cec86841b2"), "id" : "002", "amount" : 2, "price" : 10, "ok" : true }

{ "_id" : ObjectId("5b50388dff7043cec86841b3"), "id" : "003", "amount" : 3, "price" : 20.3, "ok" : true }

> db.test.aggregate(

... {

...   $group:{

...       _id:'$id',

...       total:{$sum:"$amount"}

...       }

...   })

{ "_id" : "003", "total" : 6 }

{ "_id" : "002", "total" : 12 }

{ "_id" : "001", "total" : 10 }

說明:_id:'$id',id為分類欄位名,total為統計結果欄位名,$sum為求和運算子號 ,$amount為求和欄位。




2.map-reduce法:

> var chenfeng=db.test.mapReduce(

... function(){

... emit(this.id,this.amount)

...        },

... function(key,values){

... return Array.sum(values)

... },

... {query:{ok:true},out:{replace:"result"}}

... )

> db[chenfeng.result].find()

{ "_id" : "001", "value" : 5 }

{ "_id" : "002", "value" : 6 }

{ "_id" : "003", "value" : 3 }


3.單一目標聚合法:

語法:

db.collection.count(query,options)

例如:

> db.test.distinct("id")

[ "001", "002", "003" ]

> db.test.find({ok:true}).count()

5

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15498/viewspace-2158132/,如需轉載,請註明出處,否則將追究法律責任。

相關文章