在 Debian 上配置 MongoDB 索引,本质上和操作系统无关,主要是 MongoDB Shell(mongosh)或驱动 的操作。下面按 实战流程 给你一个完整说明,从安装到索引创建、查看、优化和常见问题。
sudo systemctl status mongod
mongosh
如果使用的是旧版本:
mongo
use mydb
查看集合:
show collections
db.users.createIndex({ username: 1 })
1:升序-1:降序db.orders.createIndex({ userId: 1, createdAt: -1 })
✅ 常用于:
db.users.createIndex({ email: 1 }, { unique: true })
防止重复数据。
db.articles.createIndex({ content: "text" })
支持:
db.articles.find({ $text: { $search: "MongoDB" } })
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
✅ 用于:
db.users.createIndex(
{ username: 1 },
{ background: true }
)
避免阻塞写操作。
db.users.getIndexes()
db.users.stats().indexSizes
db.users.dropIndex({ username: 1 })
db.users.dropIndexes()
db.users.find({ username: "tom" }).explain("executionStats")
关注:
IXSCAN(索引扫描 ✅)COLLSCAN(全表扫描 ❌)sudo nano /etc/mongod.conf
常见优化项:
storage:
engine: wiredTiger
setParameter:
enableLocalhostAuthBypass: false
重启:
sudo systemctl restart mongod
✅ 只为 高频查询字段 建索引
✅ 复合索引字段顺序要匹配查询条件
✅ 避免在 写多读少 的集合建太多索引
✅ 大集合建索引使用 background: true
✅ 定期用 explain() 分析慢查询
原因:
background解决:
db.currentOp()
db.killOp(opid)
E11000 duplicate key error
解决:
db.users.createIndex(
{ email: 1 },
{ unique: true, sparse: true }
)
use shop
db.products.createIndex({ category: 1, price: -1 }, { background: true })
db.products.find(
{ category: "phone", price: { $gt: 1000 } }
).explain("executionStats")
如果你愿意,我可以:
直接把你的 查询语句 + 集合结构 发我即可。