| name | mongodb |
| description | MongoDB 数据库管理 |
| version | 1.0.0 |
| author | terminal-skills |
| tags | ["database","mongodb","nosql","document"] |
MongoDB 数据库管理
概述
MongoDB 操作、索引优化、分片集群等技能。
连接管理
mongosh
mongosh --port 27017
mongosh "mongodb://hostname:27017"
mongosh "mongodb://user:password@hostname:27017/database"
mongosh "mongodb://host1:27017,host2:27017,host3:27017/database?replicaSet=rs0"
mongosh script.js
mongosh --eval "db.collection.find()"
基础操作
数据库操作
show dbs
use mydb
db.dropDatabase()
db.stats()
集合操作
show collections
db.createCollection("users")
db.users.drop()
db.users.stats()
CRUD 操作
db.users.insertOne({ name: "John", age: 30 })
db.users.insertMany([{ name: "Jane" }, { name: "Bob" }])
db.users.find()
db.users.find({ age: { $gt: 25 } })
db.users.findOne({ name: "John" })
db.users.find().limit(10).skip(20).sort({ age: -1 })
db.users.updateOne({ name: "John" }, { $set: { age: 31 } })
db.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "minor" } })
db.users.replaceOne({ name: "John" }, { name: "John", age: 32 })
db.users.deleteOne({ name: "John" })
db.users.deleteMany({ status: "inactive" })
索引管理
db.users.getIndexes()
db.users.createIndex({ email: 1 })
db.users.createIndex({ name: 1, age: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ location: "2dsphere" })
db.users.createIndex({ content: "text" })
db.users.createIndex({ field: 1 }, { background: true })
db.users.dropIndex("email_1")
db.users.dropIndexes()
db.users.find({ email: "test@example.com" }).explain("executionStats")
聚合操作
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customer", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 10 }
])
db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}
}
])
备份与恢复
mongodump --db mydb --out /backup/
mongodump --uri="mongodb://user:pass@host:27017/mydb" --out /backup/
mongodump --db mydb --collection users --out /backup/
mongodump --db mydb --gzip --archive=/backup/mydb.gz
mongorestore --db mydb /backup/mydb/
mongorestore --uri="mongodb://user:pass@host:27017" /backup/
mongorestore --gzip --archive=/backup/mydb.gz
mongoexport --db mydb --collection users --out users.json
mongoimport --db mydb --collection users --file users.json
副本集管理
rs.status()
rs.conf()
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27017" },
{ _id: 2, host: "mongo3:27017" }
]
})
rs.add("mongo4:27017")
rs.addArb("arbiter:27017")
rs.remove("mongo4:27017")
rs.stepDown()
性能监控
db.serverStatus()
db.currentOp()
db.currentOp({ "active": true, "secs_running": { "$gt": 5 } })
db.killOp(opid)
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(10)
db.users.stats()
db.serverStatus().connections
常见场景
场景 1:查询优化
db.users.find({ email: "test@example.com" }).explain("executionStats")
db.users.find({ name: "John" }).hint({ name: 1 })
场景 2:数据迁移
db.source.aggregate([{ $out: "target" }])
db.source.find().forEach(function(doc) {
db.getSiblingDB("otherdb").target.insert(doc)
})
场景 3:批量更新
db.users.updateMany(
{ status: "pending" },
{ $set: { status: "active", updatedAt: new Date() } }
)
db.users.bulkWrite([
{ updateOne: { filter: { _id: 1 }, update: { $set: { x: 1 } } } },
{ updateOne: { filter: { _id: 2 }, update: { $set: { x: 2 } } } },
{ deleteOne: { filter: { _id: 3 } } }
])
故障排查
| 问题 | 排查方法 |
|---|
| 查询慢 | explain(), 检查索引 |
| 连接数过多 | db.serverStatus().connections |
| 内存不足 | 检查 WiredTiger 缓存配置 |
| 副本集同步延迟 | rs.status(), 检查 oplog |
| 磁盘空间 | db.stats(), compact 操作 |