MongoDB的聚合操作

作用:

1)对文档进行过滤,筛选出符合条件的文档;

2)数据处理(如统计平均数,求和等)

3)对文档进行变换,改变文档的输出结构。

 

 

语法:

db.collection.aggregate(pipeline, options)

pipeline  数组格式,由多个节点组成的管道(条件过滤、分组操作等)

options   选项

字段

类型

explain

boolean

allowDiskUse

boolean

cursor

document

bypassDocumentValidation

boolean

readConcern

document

collation

 

document

 

 

聚合的表达式:

表达式

描述

$sum

计算总和。

$avg

计算平均值

$min

获取集合中所有文档对应值得最小值。

$max

获取集合中所有文档对应值得最大值。

$push

在结果文档中插入值到一个数组中。

$addToSet

在结果文档中插入值到一个数组中,但不创建副本。

$first

根据资源文档的排序获取第一个文档数据。

$last

根据资源文档的排序获取最后一个文档数据

 

聚合中常用的几个操作:

$project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。

$match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。

$limit:用来限制MongoDB聚合管道返回的文档数。

$skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。

$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。

$group:将集合中的文档分组,可用于统计结果。

$sort:将输入文档排序后输出。

$geoNear:输出接近某一地理位置的有序文档。

 

 

 

 

例如:

{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }

{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }

{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }

{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }

{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

 

 

db.orders.aggregate([

                    { $match: { status: "A" } },

                    { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },

                    { $sort: { total: -1 } }

                   ])

 

//status字段的值为 A,cust_id分组,计算amount的和,并根据total的降序排列

 

结果:    { "_id" : "xyz1", "total" : 100 }

  { "_id" : "abc1", "total" : 75 }

 

 

 


你可能感兴趣的:(数据库)