在 Debian 上给 MongoDB 设置索引,本质和在其他系统上一样,核心是用 MongoDB Shell(mongosh) 或程序驱动来建索引。下面按“从安装到建索引”给你一个实用流程。
在 Debian 上常见两种安装方式:
mongosh
或
mongo
能进入 > 命令行就 OK。
systemctl status mongod
mongosh
use mydb
db.users.createIndex({ username: 1 })
1 升序-1 降序db.orders.createIndex({ user_id: 1, created_at: -1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ age: 1 }, { background: true })
db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 86400 }
)
db.users.getIndexes()
查看索引使用情况:
db.users.find({ username: "tom" }).explain("executionStats")
db.users.dropIndex("username_1")
或按字段删:
db.users.dropIndex({ username: 1 })
background: true确保用户有:
readWrite + dbAdmin
/etc/mongod.conf
await db.collection("users").createIndex({ email: 1 }, { unique: true });
db.users.create_index([("username", 1)])
如果你愿意,可以告诉我:
我可以帮你 设计最合适的索引方案。