在 Linux 上配置 MongoDB 索引,通常包括连接 MongoDB、创建索引、查看/删除索引,以及在配置文件中相关的性能/行为设置。下面分几个层次说明。
mongo
# 或指定端口/用户
mongo -u username -p password --authenticationDatabase admin
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.articles.createIndex({ content: "text" })
db.logs.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
db.collection.getIndexes()
db.collection.dropIndex("index_name")
# 或按字段删除
db.collection.dropIndex({ username: 1 })
MongoDB 配置文件通常在:
/etc/mongod.conf
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1
⚠️ 索引本身不在配置文件中定义,而是在数据库中创建
MongoDB 索引依赖内存:
free -h
确保 WiredTiger 缓存足够:
storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4
ulimit -n 64000
或在 /etc/security/limits.conf:
mongod soft nofile 64000
mongod hard nofile 64000
db.bigdata.createIndex({ field: 1 }, { background: true })
如果你用的是 MongoDB 6+
mongosh
命令与 mongo 基本一致。
如果你有具体场景(如:千万级数据、分片集群、Docker、定时任务),我可以给你更针对性的索引方案。