温馨提示×

centos mongodb如何配索引

小樊
41
2026-10-14 15:54:17
栏目: 云计算

在 CentOS 上配置 MongoDB 索引,其实和操作系统关系不大,主要是在 MongoDB 命令行(mongo / mongosh) 中操作。下面从「连接 → 建索引 → 查看 → 删除 → 生产建议」一步步说明。


一、登录 MongoDB(CentOS 上)

1. 本地登录

mongo
# 或新版
mongosh

2. 指定用户/库登录(常见)

mongo -u admin -p password --authenticationDatabase admin

二、选择数据库和集合

use testdb
db.users.find().limit(1)

三、创建索引(重点)

1. 单列索引

db.users.createIndex({ username: 1 })
  • 1:升序
  • -1:降序

2. 复合索引

db.users.createIndex({ age: 1, username: -1 })

3. 唯一索引

db.users.createIndex({ email: 1 }, { unique: true })

4. 后台创建索引(CentOS 生产环境推荐)

db.users.createIndex({ createTime: -1 }, { background: true })

✅ 避免锁表(MongoDB 4.2+ 已默认不阻塞写)


5. 文本索引(全文搜索)

db.articles.createIndex({ content: "text" })

6. TTL 索引(自动过期)

db.logs.createIndex({ createTime: 1 }, { expireAfterSeconds: 3600 })

四、查看索引

db.users.getIndexes()

查看索引大小:

db.users.totalIndexSize()

五、删除索引

按名删除

db.users.dropIndex("username_1")

删除全部(慎用)

db.users.dropIndexes()

六、CentOS 上的常见注意事项

1. MongoDB 配置文件位置

/etc/mongod.conf

2. 重启 MongoDB

systemctl restart mongod

3. 生产建议

  • ✅ 给 find 常用字段建索引
  • ❌ 不要给所有字段建索引
  • ✅ 用 explain() 验证索引是否生效
db.users.find({ username: "tom" }).explain("executionStats")

七、示例:完整流程

use shop
db.orders.createIndex({ userId: 1, createTime: -1 }, { background: true })
db.orders.getIndexes()

如果你愿意,可以告诉我:

  • MongoDB 版本(4.x / 5.x / 6.x / 7.x)
  • 数据量 & 查询场景(如订单、日志、用户)
  • 是否是 生产环境

我可以帮你设计最合适的索引方案。

0 踩