MongoDB笔记 聚合(详细)

Posted Aurora1217

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MongoDB笔记 聚合(详细)相关的知识,希望对你有一定的参考价值。

三种聚合的方法

1.管道聚合方法

2.map-reduce方法

3.单一目标聚合方法


聚合操作主要用于处理数据并返回计算结果。聚合操作将来自多个文档的值组合在一起,按条件分组后,再进行一系列操作(如求和、平均值、最大值、最小值)以返回单个结果。

以下例子所使用的集合里面的文档

> db.sale_detail.insert([
... {goodsid:"1001",amount:2,price:10.2,ok:false},
... {goodsid:"1001",amount:3,price:14.8,ok:false},
... {goodsid:"1002",amount:10,price:50,ok:false},
... {goodsid:"1002",amount:2,price:10,ok:true}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 4,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.sale_detail.find().pretty()
{
        "_id" : ObjectId("6094fcaf591ccad73c1e27ca"),
        "goodsid" : "1001",
        "amount" : 2,
        "price" : 10.2,
        "ok" : false
}
{
        "_id" : ObjectId("6094fcaf591ccad73c1e27cb"),
        "goodsid" : "1001",
        "amount" : 3,
        "price" : 14.8,
        "ok" : false
}
{
        "_id" : ObjectId("6094fcaf591ccad73c1e27cc"),
        "goodsid" : "1002",
        "amount" : 10,
        "price" : 50,
        "ok" : false
}
{
        "_id" : ObjectId("6094fcaf591ccad73c1e27cd"),
        "goodsid" : "1002",
        "amount" : 2,
        "price" : 10,
        "ok" : true
}

1.管道聚合方法

语法:

db.collection_name.aggregate([
    {$match:{<query>}},
    {$group:{<field1>:<field2>}}
])

命令说明:
field1:分类字段
field2:含各种统计操作符的数值型字段
统计操作符:$sum、$avg、$min、$max
           $push、$addToSet、$first、$last
aggregate命令作用类似SQL语言里的groupby语句的使用方法

实例:

(1)$sum

> db.sale_detail.aggregate([
... {$match:{ok:false}},
... {$group:{_id:"$goodsid",total:{$sum:"$amount"}}}
... ])
{ "_id" : "1002", "total" : 10 }
{ "_id" : "1001", "total" : 5 }

(2)$avg

> db.sale_detail.aggregate([
... {$match:{$or:[{ok:false},{goodsid:"1002"}]}},
... {$group:{_id:"$goodsid",avarage:{$avg:"$amount"}}}
... ])
{ "_id" : "1002", "avarage" : 6 }
{ "_id" : "1001", "avarage" : 2.5 }

(3)$min

> db.sale_detail.aggregate([
... {$match:{ok:false}},
... {$group:{_id:"$goodsid",min:{$min:"$amount"}}}
... ])
{ "_id" : "1002", "min" : 10 }
{ "_id" : "1001", "min" : 2 }

(4)$max

> db.sale_detail.aggregate([
... {$match:{ok:false}},
... {$group:{_id:"$goodsid",max:{$max:"$amount"}}}
... ])
{ "_id" : "1002", "max" : 10 }
{ "_id" : "1001", "max" : 3 }

(5)$push

> db.sale_detail.aggregate([
... {$match:{price:{$lt:20}}}
... ,{$group:{_id:"$goodsid",push:{$push:"$price"}}}
... ])
{ "_id" : "1002", "push" : [ 10 ] }
{ "_id" : "1001", "push" : [ 10.2, 14.8 ] }

(6)$addToSet

> db.sale_detail.aggregate([
... {$match:{price:{$lt:20}}}
... ,{$group:{_id:"$goodsid",addtoset:{$addToSet:"$price"}}}
... ])
{ "_id" : "1002", "addtoset" : [ 10 ] }
{ "_id" : "1001", "addtoset" : [ 14.8, 10.2 ] }

(7)$first

> db.sale_detail.aggregate([
... {$match:{price:{$gte:10.2}}},
... {$group:{_id:"$goodsid",first:{$first:"$price"}}}
... ])
{ "_id" : "1002", "first" : 50 }
{ "_id" : "1001", "first" : 10.2 }

(8)$last

> db.sale_detail.aggregate([
... {$match:{price:{$gte:10.2}}},
... {$group:{_id:"$goodsid",last:{$last:"$price"}}}
... ])
{ "_id" : "1002", "last" : 50 }
{ "_id" : "1001", "last" : 14.8 }

2.map-reduce方法

语法:

db.collection_name.mapReduce(
    function(){emit(<this.field1>,<this.field2>)},       
    function(key,values){return array.sum(values)},
    {query:{<field>},out:<resultname>}
)

命令说明:
function(){emit(<this.field1>,<this.field2>)} 把集合对应字段<field1><field2>进行map(映射)操作,并作为reduce函数输入参数
function(key,values){return array.sum(values)} 进行reduce(规约)操作,求得sum值,把values数组转换成一个单一的值value
query:设置筛选条件,满足条件才调用map方法
out:统计结果的存放集合,如果不指定则使用临时集合,但在客户端断开之后自动删除

实例:

> var arr = db.sale_detail.mapReduce(
... function(){emit(this.goodsid,this.price)},
... function(key,values){return Array.sum(values)},
... {query:{ok:false},out:{replace:"result"}}
... )
> db[arr.result].find()
{ "_id" : "1001", "value" : 25 }
{ "_id" : "1002", "value" : 50 }
> show collections
books
goodsbaseinf
order
result
sale_detail

3.单一目标聚合方法

语法:

db.collection_name.count(<query>,<options>)
db.collection_name.distinct("key")

命令说明:
query:查询条件
options:参数
   -limit 限制要计数的文档的最大数量
   -skip  计数前要跳过的文档数

单一目标聚合方法,可以直接在find后加点使用

实例:

(1)count

> db.sale_detail.count({price:{$gte:10.2}})
3
> db.sale_detail.count({price:{$gte:10.2}},{skip:1})
2
> db.sale_detail.count({price:{$gte:10.2}},{limit:1})
1
> db.sale_detail.count({price:{$gte:10.2}},{limit:2})
2

(2)distinct

> db.sale_detail.distinct("price")
[ 10.2, 14.8, 50, 10 ]
> db.sale_detail.distinct("amount")
[ 2, 3, 10 ]

(3)find

> db.sale_detail.find({price:{$gt:10}}).count()
3
> db.sale_detail.find({price:{$gt:10.2}}).count()
2

下一篇:MongoDB笔记(九) 集合操作

以上是关于MongoDB笔记 聚合(详细)的主要内容,如果未能解决你的问题,请参考以下文章

Mongodb聚合操作之读书笔记

详细教程一文参透MongoDB聚合查询

[第16期] mongoDB 干货笔记(mongoose/增删改查/聚合/索引/连接/备份与恢复/监控等)

笔记

mongodb Aggregation聚合操作之$facet

mongodb3 之单一用途聚合