```
db.users.aggregate([
{
$match:{
age:{$exists:true}
}
}
,{
$group:{
_id:null //被匹配的任何記錄一起參與同一個分組
,totalAge:{
$sum:"$age"
}
,avg:{
$avg:"$age"
}
}
}
]);
```
```
db.users.aggregate([
{
$match:{
age:{$exists:true}
,name:{$exists:true}
}
}
,{
$group:{
_id:"$name" //被匹配的記錄按照name來進行分組
,totalAge:{
$sum:"$age"
}
,avg:{
$avg:"$age"
}
}
}
]);
```
如果hobbies是個數組,將會把一條記錄分拆成n條
```
db.users.aggregate([
{
$match:{
hobbies:{$exists:true}
}
}
,{
$unwind:"$hobbies"
}
]);
```