温馨提示×

debian mongodb如何配索引

小樊
43
2026-09-29 13:53:44
栏目: 云计算

在 Debian 上配置 MongoDB 索引,核心步骤是安装 MongoDB → 连接 MongoDB → 使用 createIndex 创建索引。下面按实战流程说明。


一、Debian 上安装 MongoDB(简要)

以 Debian 11/12 为例:

sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable mongod
sudo systemctl start mongod

验证:

mongo --version
# 或新版本
mongosh --version

二、连接 MongoDB

mongosh
# 或
mongo

选择数据库:

use testdb

三、MongoDB 索引类型与配置方法

1️⃣ 单字段索引(最常用)

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

2️⃣ 复合索引

db.orders.createIndex({ user_id: 1, 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 })

四、查看与管理索引

查看索引:

db.users.getIndexes()

删除索引:

db.users.dropIndex("username_1")

删除所有索引(保留 _id):

db.users.dropIndexes()

五、生产环境建议(Debian + MongoDB)

✅ 使用 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 })

如果你有:

  • 具体表结构
  • 查询场景(慢查询)
  • MongoDB 版本(4.x / 5.x / 6.x / 7.x)

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

0 踩