MongoDB 是一种流行的 NoSQL 数据库,因其能够使用 JSON(BSON)文档格式存储非结构化或半结构化数据的能力而受到广泛使用。
它有很多高级操作。
1:MongoDB 的一个重要功能是聚合管道,它可以对数据进行深入处理。通过聚合管道,数据可以在流水线的不同阶段中逐步处理,例如过滤、分组、聚合计算和排序等操作。
2:MongoDB 还具有 $lookup 功能,可以让用户将来自不同集合的数据合并,类似于关系型数据库中的 JOIN 操作。
3:为了处理大量数据,MongoDB 使用分片,这允许将数据分布到多个服务器中。分片通过将数据分成不同的部分(chunks)并分布到多个服务器来保持数据库的性能和可扩展性。这使得 MongoDB 可以处理大量数据而不影响数据访问速度。
4:MongoDB 的全文搜索功能使用户可以在集合中基于文本内容进行搜索,通过 $text 操作符和文本索引支持,用户能够更轻松地根据文本字段中的关键词搜索文档。
5:MongoDB 还提供了多种更新操作符,允许用户选择性地更新数据。比如 inc 和 $push 等操作符可以用于更改文档中的值、向数组中添加新数据,或自动计算数值,而无需手动提取和更改数据。
6:在查询优化方面,MongoDB 支持索引的使用,以加快数据检索速度。用户可以创建多种类型的索引,例如单字段索引、多字段复合索引或文本索引,以提升查询性能。
7:从版本 4.0 开始,MongoDB 支持多文档事务,这使得可以在一个原子事务中执行多个操作。这对于确保数据一致性非常重要,尤其是在需要同时更新多个文档的应用场景中。
下面举几个例子。
1:先填充数据:
from pymongo import MongoClient, InsertOne
client = MongoClient('mongodb+srv:///')
db = client['university_db']
courses_collection = db['courses'] # courses 集合
operations = [
InsertOne({'course': 'Math 101', 'enrollments': 30, 'department': 'Mathematics'}),
InsertOne({'course': 'CS 102', 'enrollments': 25, 'department': 'Computer Science'}),
InsertOne({'course': 'History 201', 'enrollments': 20, 'department': 'History'}),
InsertOne({'course': 'Physics 202', 'enrollments': 15, 'department': 'Physics'})
]
# 批量操作
courses_collection.bulk_write(operations)
2:复杂的过滤和查询
查询注册人数超过 20 的课程:
for course in courses_collection.find({'enrollments': {'$gt': 20}}):
print(course)
查询属于 'Computer Science' 或 'Mathematics' 部门的课程:
for course in courses_collection.find({'department': {'$in': ['Computer Science', 'Mathematics']}}):
print(course)
3:聚合操作
对部门进行分组,然后查询每个部门的平均人数(新字段average_enrollment):
pipeline = [
{'$group': {'_id': '$department', 'average_enrollment': {'$avg': '$enrollments'}}}
]
for result in courses_collection.aggregate(pipeline):
print(result)
返回:
[
{"_id": "Computer Science", "max_enrollment": 25},
{"_id": "Physics", "max_enrollment": 15},
{"_id": "History", "max_enrollment": 20},
{"_id": "Mathematics", "max_enrollment": 30}
]
返回每个部门的最大注册人数:
pipeline = [
{'$group': {'_id': '$department', 'max_enrollment': {'$max': '$enrollments'}}}
]
for result in courses_collection.aggregate(pipeline):
print(result)
4:使用 project 和 addFields 转换数据
重命名字段:
pipeline = [
{'$project': {'course_name': '$course', 'department_name': '$department', 'enrollments': 1}}
]
for result in courses_collection.aggregate(pipeline):
print(result)
对注册人数进行分类,大于20则enrollment_category 设置为 'high',否则设置为 'low':
pipeline = [
{'$addFields': {'enrollment_category': {'$cond': {'if': {'$gt': ['$enrollments', 20]}, 'then': 'high', 'else': 'low'}}}}
]
for result in courses_collection.aggregate(pipeline):
print(result)
6:$lookup 进行多表join操作
pipeline = [
{
'$lookup': {
'from': 'students', #目标集合
'localField': 'course',#关联字段 courses集合course字段
'foreignField': 'course', #关联字段
'as': 'student_enrollments'#存储结果
}
},
{
#控制哪些字段现实
'$project': {
'course': 1,
'department': 1,
'enrollments': 1,
'student_enrollments': 1
}
]
result = courses_collection.aggregate(pipeline)
for doc in result:
print(f"Kursus: {doc['course']}, Departemen: {doc['department']}, Jumlah Pendaftar: {doc['enrollments']}")
for student in doc['student_enrollments']:
print(f" - {student['name']}")
print("\n")
over!




