最近有把一个小项目的底层数据库由 MySQL 修改成 MongoDB,借此更进一步熟悉了 Aggregation Pipeline Stages
本文仅包含翻译小项目 SQL 版本所需的 MongoDB Aggregation Pipeline Stages 知识,成文时 MongoDB 最新版本为 V4.2
db.collection.aggregate( [ { <stage> }, ... ] )
注:除了 o u t 、 out、 out、merge、$geoNear 所有 stage(阶段)均可在 pipeline(管道)中出现多次,意味着本文所提这些均可出现多次
Examples
示例仅演示本文相关 stage 主要用法,详细请访问各个 stage 的官方文档
db.message.insertMany([
{"id": 1,"num": 2},
{"id": 1,"num": 4},
{"id": 2,"num": 6},
{"id": 2,"num": 4},
{"id": 2,"num": 2},
{"id": 3,"num": 2}
]);
db.user.insertMany([
{"id": 1,"name": "n1"},
{"id": 2,"name": "n2"},
{"id": 3,"name": "n3"}
]);
db.message.aggregate([{
$match: {
id: 2
}
}, {
$sort: {
num: 1
}
}, {
$limi