温馨提示×

debian mongodb怎样配索引

小樊
45
2026-09-08 11:08:24
栏目: 云计算

在 Debian 上配置 MongoDB 索引,主要分为 连接 MongoDB → 选择数据库和集合 → 创建/查看/删除索引。下面按实战步骤说明。


一、前提:Debian 上已安装并运行 MongoDB

常见检查:

sudo systemctl status mongod
mongo --version

新版本 MongoDB(5+)客户端可能是 mongosh 而不是 mongo

mongosh

二、连接 MongoDB

mongosh

或指定 IP / 端口:

mongosh "mongodb://127.0.0.1:27017"

三、选择数据库和集合

use testdb

查看集合:

show collections

四、创建索引(核心)

1️⃣ 单字段索引

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

查看索引:

db.users.getIndexes()

2️⃣ 复合索引(最常用)

db.orders.createIndex({ user_id: 1, created_at: -1 })

✅ 适合:

db.orders.find({ user_id: 1001 }).sort({ created_at: -1 })

3️⃣ 唯一索引(防重复)

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

4️⃣ 文本索引(全文搜索)

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

查询:

db.articles.find({ $text: { $search: "mongodb" } })

5️⃣ TTL 索引(自动过期)

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

⏱ 一小时前的数据自动删除


6️⃣ 后台创建索引(生产推荐)

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

MongoDB 4.2+ 默认异步,不再需要 background


五、查看 & 删除索引

查看:

db.collection.getIndexes()

删除某个索引:

db.users.dropIndex("username_1")

删除全部(⚠危险):

db.users.dropIndexes()

六、Debian 生产环境建议

✅ 在 配置文件中开启慢查询日志

sudo nano /etc/mongod.conf
operationProfiling:
  slowOpThresholdMs: 100
  mode: slowOp

重启:

sudo systemctl restart mongod

✅ 用 explain() 验证索引是否生效:

db.users.find({ username: "tom" }).explain("executionStats")

七、常见错误

❌ 索引字段类型不一致
❌ 复合索引顺序不对
❌ 在超大集合上同步建索引(锁表)


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

  • MongoDB 版本
  • 数据结构示例
  • 查询语句

我可以帮你 设计最优索引方案

0