MongoDB 常用命令与操作手册
MongoDB 常用命令与操作手册
整体架构概览
Mermaid diagram will appear here
flowchart TD
Client[客户端] --> MongoShell[mongo shell]
MongoShell --> AdminDB[admin 数据库]
MongoShell --> UserDB[业务数据库]
AdminDB --> Auth[认证与授权]
AdminDB --> Users[用户管理]
AdminDB --> Roles[角色管理]
UserDB --> Collections[集合 Collections]
Collections --> Documents[文档 Documents]
Documents --> Fields[字段 Fields]
核心知识体系
Markmap will appear here
# MongoDB
## 连接与认证
### 连接数据库
### 用户认证
### 角色授权
## 数据库操作
### 查看数据库
### 切换数据库
## 集合操作
### 查看集合
### 创建集合
## CRUD 操作
### 插入数据
### 查询数据
### 更新数据
### 删除数据
## 数据导出导入
### mongodump
### mongorestore
## 运维管理
### 用户管理
### 性能监控
---
1. 连接与认证
1.1 连接数据库
# 本地连接
mongo --host 127.0.0.1 --port 27017
# 带认证连接
mongo -u notedeepAdmin -p --authenticationDatabase admin
1.2 用户认证
use admin
db.auth('notedeepAdmin', 'pwd')
⚠️ 注意:认证必须在 `admin` 数据库下进行,认证成功后可切换到其他数据库操作。
1.3 给用户赋予角色
db.grantRolesToUser('notedeepAdmin', [
{ role: 'dbOwner', db: 'notedeep' }
])
常用角色说明
角色 | 权限范围 | 说明 |
`read` | 单库 | 只读权限 |
`readWrite` | 单库 | 读写权限 |
`dbAdmin` | 单库 | 数据库管理权限 |
`dbOwner` | 单库 | 数据库所有者(最高单库权限) |
`userAdmin` | 单库 | 用户管理权限 |
`clusterAdmin` | 集群 | 集群管理最高权限 |
`root` | 全局 | 超级管理员 |
---
2. 数据库与集合操作
2.1 数据库操作
// 查看所有数据库
show dbs
// 切换/创建数据库
use notedeep
// 查看当前数据库
db.getName()
// 删除当前数据库
db.dropDatabase()
2.2 集合操作
// 查看所有集合
show collections
// 创建集合(显式)
db.createCollection("myCollection", { capped: true, size: 6142800, max: 10000 })
// 删除集合
db.collection.drop()
---
3. CRUD 操作
CRUD 操作流程
Mermaid diagram will appear here
flowchart LR
C[Create 插入] --> R[Read 查询]
R --> U[Update 更新]
U --> D[Delete 删除]
D -.-> C
3.1 插入数据(Create)
// 插入单条文档
db.collection.insert({ name: "test", value: 1 })
// 推荐写法
db.collection.insertOne({ name: "test", value: 1 })
// 插入多条文档
db.collection.insertMany([
{ name: "test1", value: 1 },
{ name: "test2", value: 2 }
])
实际示例:插入 Block 数据
db.block.insert({
"_id": 14,
"name": "思维导图",
"desc": "用于绘制思维导图",
"img": "https://static.notedeep.com/FvxaK2NCj7MDoBimORQXLmOUEPtj"
})
db.block.insert({
"_id": 15,
"name": "MarkDown",
"desc": "用于插入MarkDown段落",
"img": "https://static.notedeep.com/FqifKVakIC_3IzA8cgWMorcPEhpw"
})
3.2 查询数据(Read)
// 查询所有文档
db.collection.find()
// 条件查询
db.collection.find({ name: "思维导图" })
// 格式化输出
db.collection.find().pretty()
// 只返回指定字段
db.collection.find({}, { name: 1, desc: 1, _id: 0 })
// 限制返回条数
db.collection.find().limit(10)
// 排序(1 升序,-1 降序)
db.collection.find().sort({ _id: -1 })
常用查询操作符
操作符 | 语法 | 说明 |
等于 | `{ field: value }` | 精确匹配 |
不等于 | `{ field: { $ne: value } }` | 排除匹配 |
大于 | `{ field: { $gt: value } }` | 大于 |
大于等于 | `{ field: { $gte: value } }` | 大于等于 |
小于 | `{ field: { $lt: value } }` | 小于 |
小于等于 | `{ field: { $lte: value } }` | 小于等于 |
包含 | `{ field: { $in: [v1, v2] } }` | 在列表中 |
不包含 | `{ field: { $nin: [v1, v2] } }` | 不在列表中 |
模糊匹配 | `{ field: /regex/ }` | 正则匹配 |
3.3 更新数据(Update)
// 更新单个字段
db.block.update(
{ _id: 13 },
{ $set: { desc: "用于绘制BPMN图、业务流程模型和标记法" } }
)
// 推荐写法
db.collection.updateOne(
{ _id: 13 },
{ $set: { desc: "用于绘制BPMN图" } }
)
// 更新多条
db.collection.updateMany(
{ status: "active" },
{ $set: { status: "inactive" } }
)
// 替换整个文档
db.collection.replaceOne({ _id: 13 }, { name: "BPMN", desc: "业务流程" })
更新操作符一览
操作符 | 说明 | 示例 |
`$set` | 设置字段值 | `{ $set: { name: "new" } }` |
`$unset` | 删除字段 | `{ $unset: { name: "" } }` |
`$inc` | 字段值递增 | `{ $inc: { count: 1 } }` |
`$push` | 数组追加元素 | `{ $push: { tags: "new" } }` |
`$pull` | 数组移除元素 | `{ $pull: { tags: "old" } }` |
`$rename` | 重命名字段 | `{ $rename: { old: "new" } }` |
3.4 删除数据(Delete)
// 删除匹配文档
db.collection.remove({ name: "test" })
// 推荐写法:删除单条
db.collection.deleteOne({ _id: 13 })
// 删除多条
db.collection.deleteMany({ status: "inactive" })
⚠️ 警告:删除操作不可逆,请谨慎使用!建议先 `find` 确认后再执行删除。
---
4. 数据导出与导入
4.1 mongodump 导出
# 导出所有数据库
mongodump -h 127.0.0.1 --port 27017 -u notedeepAdmin -p
# 导出指定数据库
mongodump -h 127.0.0.1 --port 27017 -u notedeepAdmin -p -d notedeep -o /backup/
# 导出指定集合
mongodump -h 127.0.0.1 --port 27017 -u notedeepAdmin -p -d notedeep -c block -o /backup/
4.2 mongorestore 导入
# 恢复所有数据库
mongorestore -h 127.0.0.1 --port 27017 -u notedeepAdmin -p /backup/
# 恢复指定数据库
mongorestore -h 127.0.0.1 --port 27017 -u notedeepAdmin -p -d notedeep /backup/notedeep/
备份恢复流程
Mermaid diagram will appear here
sequenceDiagram
participant OP as 运维人员
participant SRC as 源数据库
participant FS as 文件系统
participant DST as 目标数据库
OP->>SRC: mongodump 导出
SRC->>FS: 写入 BSON 文件
Note over FS: /backup/notedeep/*.bson
OP->>FS: mongorestore 导入
FS->>DST: 写入数据
Note over DST: 数据恢复完成
---
5. 聚合管道(Aggregation Pipeline)
Mermaid diagram will appear here
flowchart LR
A[$match 过滤] --> B[$group 分组]
B --> C[$sort 排序]
C --> D[$project 投影]
D --> E[$limit 限制]
db.collection.aggregate([
{ $match: { status: "active" } },
{ $group: { _id: "$category", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $project: { _id: 0, category: "$_id", total: 1 } },
{ $limit: 10 }
])
常用聚合阶段
阶段 | 说明 |
`$match` | 过滤文档,类似 find 的查询条件 |
`$group` | 按字段分组并计算聚合值 |
`$sort` | 对结果排序 |
`$project` | 修改文档结构,选择字段 |
`$limit` | 限制返回文档数 |
`$skip` | 跳过指定数量文档 |
`$unwind` | 展开数组字段 |
`$lookup` | 左连接,关联其他集合 |
---
6. 索引管理
// 创建索引
db.collection.createIndex({ name: 1 }) // 单字段索引(升序)
db.collection.createIndex({ name: 1, age: -1 }) // 复合索引
db.collection.createIndex({ desc: "text" }) // 文本索引
// 查看索引
db.collection.getIndexes()
// 删除索引
db.collection.dropIndex("name_1")
db.collection.dropIndexes() // 删除所有索引(除 _id)
---
7. 常用运维命令速查
命令 | 说明 |
`db.serverStatus()` | 查看服务器状态 |
`db.stats()` | 查看当前数据库统计 |
`db.collection.stats()` | 查看集合统计 |
`db.collection.count()` | 统计文档数量 |
`db.currentOp()` | 查看当前正在执行的操作 |
`rs.status()` | 查看副本集状态 |
`sh.status()` | 查看分片状态 |
---
官方文档
最佳实践
- 索引设计:为高频查询字段创建索引,避免全表扫描
- 文档设计:合理使用嵌入文档 vs 引用文档
- 写入策略:根据业务需求选择 `w:1` / `w:majority`
- 分片键:选择基数大、分布均匀的字段作为分片键
- 连接池:合理配置连接池大小,避免连接耗尽