聚合(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/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/15498/viewspace-2158132/