Loading...
Loading...
Compare original and translation side by side
undefinedundefinedundefinedundefined// Connect without auth first
// mongosh
use admin
// Create admin user
db.createUser({
user: "admin",
pwd: "strong_admin_password",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
// Create an application-scoped user
use mydb
db.createUser({
user: "myapp",
pwd: "strong_app_password",
roles: [{ role: "readWrite", db: "mydb" }]
})/etc/mongod.confsecurity:
authorization: enabledsudo systemctl restart mongod// Connect without auth first
// mongosh
use admin
// Create admin user
db.createUser({
user: "admin",
pwd: "strong_admin_password",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
// Create an application-scoped user
use mydb
db.createUser({
user: "myapp",
pwd: "strong_app_password",
roles: [{ role: "readWrite", db: "mydb" }]
})/etc/mongod.confsecurity:
authorization: enabledsudo systemctl restart mongodundefinedundefined// Show databases and collections
show dbs
use mydb
show collections
// Insert documents
db.users.insertOne({ name: "Alice", email: "alice@example.com", age: 30 })
db.users.insertMany([
{ name: "Bob", email: "bob@example.com", age: 25 },
{ name: "Carol", email: "carol@example.com", age: 35 }
])
// Query documents
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).limit(10)
db.users.findOne({ email: "alice@example.com" })
db.users.countDocuments({ age: { $gte: 30 } })
// Update
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { age: 31 }, $currentDate: { updatedAt: true } }
)
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { tier: "junior" } }
)
// Delete
db.users.deleteOne({ email: "bob@example.com" })
db.users.deleteMany({ tier: "junior" })// Show databases and collections
show dbs
use mydb
show collections
// Insert documents
db.users.insertOne({ name: "Alice", email: "alice@example.com", age: 30 })
db.users.insertMany([
{ name: "Bob", email: "bob@example.com", age: 25 },
{ name: "Carol", email: "carol@example.com", age: 35 }
])
// Query documents
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).limit(10)
db.users.findOne({ email: "alice@example.com" })
db.users.countDocuments({ age: { $gte: 30 } })
// Update
db.users.updateOne(
{ email: "alice@example.com" },
{ $set: { age: 31 }, $currentDate: { updatedAt: true } }
)
db.users.updateMany(
{ age: { $lt: 30 } },
{ $set: { tier: "junior" } }
)
// Delete
db.users.deleteOne({ email: "bob@example.com" })
db.users.deleteMany({ tier: "junior" })// Single-field index
db.users.createIndex({ email: 1 }, { unique: true })
// Compound index
db.orders.createIndex({ userId: 1, createdAt: -1 })
// Text index for search
db.articles.createIndex({ title: "text", body: "text" })
db.articles.find({ $text: { $search: "mongodb scaling" } })
// TTL index — auto-delete documents after 30 days
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 })
// List indexes
db.users.getIndexes()
// Drop an index
db.users.dropIndex("email_1")
// Explain a query to verify index usage
db.orders.find({ userId: 42 }).explain("executionStats")// Single-field index
db.users.createIndex({ email: 1 }, { unique: true })
// Compound index
db.orders.createIndex({ userId: 1, createdAt: -1 })
// Text index for search
db.articles.createIndex({ title: "text", body: "text" })
db.articles.find({ $text: { $search: "mongodb scaling" } })
// TTL index — auto-delete documents after 30 days
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 2592000 })
// List indexes
db.users.getIndexes()
// Drop an index
db.users.dropIndex("email_1")
// Explain a query to verify index usage
db.orders.find({ userId: 42 }).explain("executionStats")// Revenue per status
db.orders.aggregate([
{ $group: {
_id: "$status",
totalRevenue: { $sum: "$total" },
count: { $sum: 1 }
}},
{ $sort: { totalRevenue: -1 } }
])
// Top 5 customers by order value (with a join)
db.orders.aggregate([
{ $group: {
_id: "$userId",
spent: { $sum: "$total" },
orderCount: { $sum: 1 }
}},
{ $sort: { spent: -1 } },
{ $limit: 5 },
{ $lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "user"
}},
{ $unwind: "$user" },
{ $project: {
_id: 0,
name: "$user.name",
email: "$user.email",
spent: 1,
orderCount: 1
}}
])
// Daily signup trend
db.users.aggregate([
{ $group: {
_id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
signups: { $sum: 1 }
}},
{ $sort: { _id: 1 } },
{ $limit: 30 }
])// Revenue per status
db.orders.aggregate([
{ $group: {
_id: "$status",
totalRevenue: { $sum: "$total" },
count: { $sum: 1 }
}},
{ $sort: { totalRevenue: -1 } }
])
// Top 5 customers by order value (with a join)
db.orders.aggregate([
{ $group: {
_id: "$userId",
spent: { $sum: "$total" },
orderCount: { $sum: 1 }
}},
{ $sort: { spent: -1 } },
{ $limit: 5 },
{ $lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "user"
}},
{ $unwind: "$user" },
{ $project: {
_id: 0,
name: "$user.name",
email: "$user.email",
spent: 1,
orderCount: 1
}}
])
// Daily signup trend
db.users.aggregate([
{ $group: {
_id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
signups: { $sum: 1 }
}},
{ $sort: { _id: 1 } },
{ $limit: 30 }
])undefinedundefined
```bash
```bashundefinedundefined// Connect to the first member
// mongosh --port 27017
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017", priority: 2 },
{ _id: 1, host: "mongo2:27017", priority: 1 },
{ _id: 2, host: "mongo3:27017", priority: 1 }
]
})
// Check status
rs.status()
// View replication lag per member
rs.printReplicationInfo()
rs.printSecondaryReplicationInfo()// Connect to the first member
// mongosh --port 27017
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017", priority: 2 },
{ _id: 1, host: "mongo2:27017", priority: 1 },
{ _id: 2, host: "mongo3:27017", priority: 1 }
]
})
// Check status
rs.status()
// View replication lag per member
rs.printReplicationInfo()
rs.printSecondaryReplicationInfo()undefinedundefinedundefinedundefinedundefinedundefined
```bash
```bashundefinedundefined// Server status summary
db.serverStatus().connections
db.serverStatus().opcounters
// Current operations (look for long-running queries)
db.currentOp({ secs_running: { $gte: 5 } })
// Collection stats
db.orders.stats()
// Index sizes
db.orders.stats().indexSizes
// Profiler — log slow queries (> 100ms)
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
// Replica set lag
rs.printSecondaryReplicationInfo()// Server status summary
db.serverStatus().connections
db.serverStatus().opcounters
// Current operations (look for long-running queries)
db.currentOp({ secs_running: { $gte: 5 } })
// Collection stats
db.orders.stats()
// Index sizes
db.orders.stats().indexSizes
// Profiler — log slow queries (> 100ms)
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
// Replica set lag
rs.printSecondaryReplicationInfo()undefinedundefinedundefinedundefined| Symptom | Likely Cause | Fix |
|---|---|---|
| Missing index on queried field | Create an appropriate index |
Replica member stuck in | Oplog window exceeded | Resync by removing data and restarting the member |
| OS file descriptor limit too low | Set |
| High memory usage | WiredTiger cache too large | Reduce |
| Slow aggregation pipelines | No index on | Add index; place |
| Authentication failure | Wrong | Specify |
| 症状 | 可能原因 | 解决方法 |
|---|---|---|
执行计划输出中出现 | 查询字段缺少索引 | 创建合适的索引 |
副本成员卡在 | Oplog窗口超出限制 | 删除数据并重新启动成员以重新同步 |
| OS文件描述符限制过低 | 在服务文件中设置 |
| 内存占用过高 | WiredTiger缓存过大 | 在配置中减小 |
| 聚合管道运行缓慢 | | 添加索引;将 |
| 认证失败 | | 对于管理员用户,指定 |