在 CentOS 上配置 MongoDB 索引,其实和操作系统关系不大,主要是在 MongoDB 命令行(mongo / mongosh) 中操作。下面从「连接 → 建索引 → 查看 → 删除 → 生产建议」一步步说明。
mongo
# 或新版
mongosh
mongo -u admin -p password --authenticationDatabase admin
use testdb
db.users.find().limit(1)
db.users.createIndex({ username: 1 })
1:升序-1:降序db.users.createIndex({ age: 1, username: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ createTime: -1 }, { background: true })
✅ 避免锁表(MongoDB 4.2+ 已默认不阻塞写)
db.articles.createIndex({ content: "text" })
db.logs.createIndex({ createTime: 1 }, { expireAfterSeconds: 3600 })
db.users.getIndexes()
查看索引大小:
db.users.totalIndexSize()
db.users.dropIndex("username_1")
db.users.dropIndexes()
/etc/mongod.conf
systemctl restart mongod
find 常用字段建索引explain() 验证索引是否生效db.users.find({ username: "tom" }).explain("executionStats")
use shop
db.orders.createIndex({ userId: 1, createTime: -1 }, { background: true })
db.orders.getIndexes()
如果你愿意,可以告诉我:
我可以帮你设计最合适的索引方案。