前言
MongoDB作为当前最流行的NoSQL数据库之一,以其灵活的文档模型、高性能和易扩展性赢得了广大开发者的青睐。本文将带您从零开始学习MongoDB,涵盖安装配置、基本操作、高级查询以及实战应用等内容。
一、什么是 MongoDB
MongoDB 是一个基于分布式文件存储的开源 NoSQL 数据库系统,它具有以下特点:
- 文档模型:数据以类似 JSON 的 BSON 格式存储,结构灵活
- 无 schema 设计:集合 (Collection) 中的文档可以有不同的结构
- 高可用性:支持副本集,提供自动故障转移
- 水平扩展:通过分片实现数据的水平扩展
- 丰富的查询功能:支持复杂查询、索引和聚合操作
二、MongoDB 基本操作
2.1 数据库操作
# 展示又有的非空数据库
show dbs
#显示当前数据库
db
#创建/切换数据库(没有则创建)
use 数据库名
#删除数据库
db.dropDatabase()
2.2 集合操作
#创建集合
db.createCollection("集合名")
#查看所有集合
show collections
#删除集合
db.集合名.drop()
2.3 文档CRUD操作
# 插入单条文档
post = {
"title": "Python and MongoDB",
"content": "PyMongo is awesome!",
"tags": ["python", "mongodb"],
"views": 100
}
insert_result = collection.insert_one(post)
print(f"插入文档ID: {insert_result.inserted_id}")
# 批量插入
posts = [
{"title": "First Post", "author": "Alice"},
{"title": "Second Post", "author": "Bob"}
]
insert_many_result = collection.insert_many(posts)
print(f"插入的文档IDs: {insert_many_result.inserted_ids}")
查询文档:
# 查询单条文档
document = collection.find_one({"author": "Alice"})
print(document)
# 查询多条文档
for doc in collection.find({"views": {"$gt": 50}}):
print(doc)
# 带条件的高级查询
results = collection.find({
"views": {"$gte": 50, "$lte": 200},
"tags": {"$in": ["python"]}
}).sort("views", -1).limit(5)
更新文档:
# 更新单条文档
update_result = collection.update_one(
{"author": "Alice"},
{"$set": {"views": 150}, "$inc": {"likes": 1}}
)
print(f"匹配到{update_result.matched_count}条,修改了{update_result.modified_count}条")
# 更新多条文档
update_many_result = collection.update_many(
{"views": {"$lt": 100}},
{"$inc": {"views": 10}}
)
# 替换文档
replace_result = collection.replace_one(
{"title": "First Post"},
{"new_title": "Updated Post", "author": "Alice", "date": "2023-01-01"}
)
删除文档:
# 删除单条文档
delete_result = collection.delete_one({"author": "Bob"})
# 删除多条文档
delete_many_result = collection.delete_many({"views": {"$lt": 50}})
三、索引与性能优化
进阶查询可有四种最基础的方法:运算符、映射、排序、分页
3.1创建索引
# 创建索引
collection.create_index([("email", 1)], unique=True) # 唯一索引
collection.create_index([("name", 1), ("age", -1)]) # 复合索引
collection.create_index([("created_at", 1)], expireAfterSeconds=3600) # TTL索引
# 查看索引
indexes = list(collection.list_indexes())
print("集合索引:")
for index in indexes:
print(f"名称: {index['name']}, 键: {index['key']}")
# 使用explain分析查询性能
explain_result = collection.find({"age": {"$gt": 25}}).explain()
print(f"查询计划: {explain_result['queryPlanner']['winningPlan']['stage']}")
3.2 复杂查询
# 使用逻辑操作符
complex_query = {
"$or": [
{"age": {"$gt": 30}},
{"occupation": "工程师"}
],
"salary": {"$gt": 10000}
}
print("年龄大于30或是工程师且工资大于10000的用户:")
for user in collection.find(complex_query):
print(f"{user['name']} - {user['occupation']} - 工资:{user.get('salary', '未知')}")
# 正则表达式查询
regex_query = {"name": {"$regex": "张", "$options": "i"}} # i表示不区分大小写
print("\n姓名中包含'张'的用户:")
for user in collection.find(regex_query):
print(user["name"])
# 数组查询
array_query = {
"hobbies": {
"$in": ["游泳", "跑步"] # 包含游泳或跑步任一爱好
}
}
print("\n喜欢游泳或跑步的用户:")
for user in collection.find(array_query):
print(f"{user['name']}: {user.get('hobbies', [])}")
排序和分页较为简单:
#排序
find({}, {"_id": 0}).sort([("age", pymongo.DESCENDING), ("name", pymongo.DESCENDING)])
find({}, {"_id": 0}).sort("age", pymongo.DESCENDING)
#分页
find({}, {"_id": 0}).limit(2)
.find({}, {"_id": 0}).skip(2).limit(1)
MongoDB 作为一个功能丰富、性能优异的文档数据库,在现代应用开发中扮演着越来越重要的角色。无论是 Web 应用、移动应用还是物联网平台,MongoDB 都能提供灵活高效的数据存储解决方案。
1249

被折叠的 条评论
为什么被折叠?



