本文共 2516 字,大约阅读时间需要 8 分钟。
一、概念
管道在Unix和Linux系统中通常用于将命令输出作为下一个命令的参数。在MongoDB中,聚合管道则用于处理和转换数据,生成新的文档信息。管道操作可以重复使用,形成复杂的数据处理流程。
聚合框架是MongoDB处理数据的高级查询语言,允许我们通过多个聚合操作将多个文档的数据转换为新的单个文档,生成不存在的信息。常见的聚合操作符包括$lookup、$match、$unwind等。
二、集合示例准备
假设我们有三个集合:student(学生)、class(班级)和course(课程),可以通过以下命令批量插入数据。
//学生集合批量插入
db.student.insertMany([ { "id": "1", "name": "小明", "age": NumberInt(12), "sex": "男", "course": ["数学", "语文", "英语"] }, { "id": "2", "name": "小章", "age": NumberInt(13), "sex": "男", "course": ["数学", "语文"] }, { "id": "3", "name": "小九", "age": NumberInt(12), "sex": "女", "course": ["数学"] } ]);
//班级集合批量插入
db.class.insertMany([ { "stuid": "1", "name": "1001", "master": "老李" }, { "stuid": "2", "name": "1001", "master": "老李" }, { "stuid": "3", "name": "1002", "master": "老程" } ]);
//课程集合批量插入
db.course.insertMany([ { "name": "数学", "master": "老李" }, { "name": "语文", "master": "老程" }, { "name": "英语", "master": "老梁" } ]);
三、操作符用法
1. $lookup
主要功能:将输入文档与其他集合关联,输出结果中添加关联字段。
基本语法:
{ $lookup: { from: "collectionName", localField: "fieldName", foreignField: "foreignFieldName", as: "alias" }}示例:将student集合与class集合关联,查询学生的班级信息。
db.getCollection("student").aggregate([ { $lookup: { from: "class", localField: "id", foreignField: "stuid", as: "student_class" } } ]);
2. $match
主要功能:过滤数据,仅返回符合条件的文档。
示例:查询小明的详细信息。
db.getCollection("student").aggregate([ { $lookup: { from: "class", localField: "id", foreignField: "stuid", as: "student_class" } }, { $match: { name: "小明" } } ]);
3. $unwind
主要功能:将文档中的数组字段拆分成多个独立文档。
示例:拆分学生的课程数组。
db.getCollection('student').aggregate([ { $unwind: "$course" } ]);
4. $project
主要功能:重新定义返回字段,控制输出结果的格式。
示例:只返回学生的姓名和年龄。
db.getCollection('student').aggregate([ { $unwind: "$course" }, { $lookup: { from: "class", localField: "id", foreignField: "stuid", as: "student_class" } }, { $match: { name: "小明" } }, { $project: { name: 1, age: 1 } } ]);
5. $limit
主要功能:限制返回的文档数量。
示例:返回前两条数据。
db.getCollection("student").aggregate([ { $lookup: { from: "class", localField: "id", foreignField: "stuid", as: "student_class" } }, { $limit: 2 } ]);
6. $skip
主要功能:跳过指定数量的文档。
示例:跳过第一个文档并返回两个数据。
db.getCollection("student").aggregate([ { $lookup: { from: "class", localField: "id", foreignField: "stuid", as: "student_class" } }, { $skip: 1 }, { $limit: 2 } ]);
7. $group
主要功能:按指定字段分组,类似于group by语句。
示例:按班主任分组统计班级人数。
db.getCollection("class").aggregate([ { $group: { _id: "$master", count: { $sum: 1 } } } ]);
8. $sort
主要功能:对查询结果进行排序。
示例:按学生ID降序排序。
db.getCollection("student").aggregate([ { $sort: { id: -1 } } ]);
转载地址:http://kchfk.baihongyu.com/