MongoDB全面入门教程:从基础到实战

前言

一、什么是 MongoDB

二、MongoDB 基本操作

2.1 数据库操作

2.2 集合操作

2.3 文档CRUD操作

 查询文档:

三、索引与性能优化

3.1创建索引

3.2 复杂查询

排序和分页较为简单:


前言

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 都能提供灵活高效的数据存储解决方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值