管道
管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数,MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
管道操作符
| 常用管道 | 解析 |
|---|---|
| $group | 将collection中的document分组,可用于统计结果 |
| $match | 过滤数据,只输出符合结果的文档 |
| $project | 修改输入文档的结构(例如重命名,增加、删除字段,创建结算结果等) |
| $sort | 将结果进行排序后输出 |
| $limit | 限制管道输出的结果个数 |
| $skip | 跳过制定数量的结果,并且返回剩下的结果 |
| $unwind | 将数组类型的字段进行拆分 |
表达式操作符
| 常用表达式 | 含义 |
|---|---|
| $sum | 计算总和,{ |
| $avg | 求平均值 |
| $min | 求min值 |
| $max | 求max值 |
| $push | 将结果文档中插入值到一个数组中 |
| $first | 根据文档的排序获取第一个文档数据 |
| $last | 同理,获取最后一个数据 |
为了便于理解,将常见的mongo的聚合操作和MySql的查询做类比:
| MongoDB聚合操作 | MySql操作/函数 |
|---|---|
| $match | where |
| $group | group by |
| $match | having |
| $project | select |
| $sort | order by |
| $limit | limit |
| $sum | sum() |
| $lookup | join |
Aggregation Pipeline 优化
- 聚合管道可以确定它是否仅需要文档中的字段的子集来获得结果。 如果是这样,管道将只使用那些必需的字段,减少通过管道的数据量
- 管道序列优化化
map-reduce

image.png
单用途集聚操作
参考资料:
MongoDB系列--深入理解MongoDB聚合(Aggregation )
数据验证
- JSON模式进行模式验证
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "address" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "must be an integer in [ 2017, 3017 ] and is required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null ],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
description: "must be a double if the field exists"
},
address: {
bsonType: "object",
required: [ "city" ],
properties: {
street: {
bsonType: "string",
description: "must be a string if the field exists"
},
city: {
bsonType: "string",
"description": "must be a string and is required"
}
}
}
}
}
}
})
- 其他查询表达式
db.createCollection( "contacts",
{ validator: { $or:
[
{ phone: { $type: "string" } },
{ email: { $regex: /@mongodb\.com$/ } },
{ status: { $in: [ "Unknown", "Incomplete" ] } }
]
}
} )