在 Debian 上配置 MongoDB 索引,核心步骤是安装 MongoDB → 连接 MongoDB → 使用 createIndex 创建索引。下面按实战流程说明。
以 Debian 11/12 为例:
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable mongod
sudo systemctl start mongod
验证:
mongo --version
# 或新版本
mongosh --version
mongosh
# 或
mongo
选择数据库:
use testdb
db.users.createIndex({ username: 1 })
1 升序-1 降序db.orders.createIndex({ user_id: 1, created_at: -1 })
⚠️ 注意字段顺序(最左前缀原则)
db.users.createIndex({ email: 1 }, { unique: true })
db.articles.createIndex({ title: "text", content: "text" })
查询:
db.articles.find({ $text: { $search: "mongodb" } })
db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
db.users.createIndex({ age: 1 }, { background: true })
查看索引:
db.users.getIndexes()
删除索引:
db.users.dropIndex("username_1")
删除所有索引(保留 _id):
db.users.dropIndexes()
✅ 使用 background: true
✅ 大表避免在业务高峰期建索引
✅ 使用 explain() 检查索引是否生效
db.users.find({ username: "tom" }).explain("executionStats")
✅ 配置 mongod.conf 限制内存(如需要)
use shop
db.products.createIndex({ category: 1, price: -1 })
db.products.createIndex({ sku: 1 }, { unique: true })
如果你有:
我可以帮你设计最优索引方案。