聚合管道阶段
-
$group
: 对文档进行分组
格式:
{$group:{
_id:<expression>,
<field1>: {<accumulator1>: <expression1>}
... ...
}}
group 括号当中属性的含义:
-
_id
: 定义分组规则 -
<field>
: 定义新字段
示例
添加测试数据,在添加之前先将之前的旧数据进行删除,删除的方式我这里不介绍自行删除,添加测试的数据脚本如下:
db.person.insert([
{name:'zs', age:10, city:'北京'},
{name:'ls', age:20, city:'上海'},
{name:'ww', age:30, city:'北京'},
{name:'zl', age:40, city:'上海'},
{name:'lnj', age:50, city:'北京'},
{name:'jjj', age:60, city:'广州'},
]);
然后就是使用 group:
db.person.aggregate([
{$group:{
_id: '$city',
totalAge: {$sum:'$age'},
avgAge: {$avg:'$age'},
minAge: {$min:'$age'},
maxAge: {$max:'$age'},
totalName: {$push:'$name'}
}}
]);