温馨提示×

linux mongodb配置怎样设置索引

小樊
39
2026-10-28 05:21:48
栏目: 云计算

在 Linux 上配置 MongoDB 索引,通常包括连接 MongoDB、创建索引、查看/删除索引,以及在配置文件中相关的性能/行为设置。下面分几个层次说明。


一、通过 MongoDB Shell 设置索引(最常用)

1. 登录 MongoDB

mongo
# 或指定端口/用户
mongo -u username -p password --authenticationDatabase admin

2. 选择数据库和集合

use mydb

3. 创建索引

单字段索引

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" })

TTL 索引(自动过期)

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

二、查看和删除索引

查看索引

db.collection.getIndexes()

删除索引

db.collection.dropIndex("index_name")
# 或按字段删除
db.collection.dropIndex({ username: 1 })

三、Linux 下 MongoDB 配置文件相关设置

MongoDB 配置文件通常在:

/etc/mongod.conf

1. 基本配置示例

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

⚠️ 索引本身不在配置文件中定义,而是在数据库中创建


四、索引性能相关配置(Linux 优化)

1. 内存(非常重要)

MongoDB 索引依赖内存:

free -h

确保 WiredTiger 缓存足够:

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4

2. 文件描述符限制(Linux)

ulimit -n 64000

或在 /etc/security/limits.conf:

mongod soft nofile 64000
mongod hard nofile 64000

五、后台创建索引(生产环境推荐)

db.bigdata.createIndex({ field: 1 }, { background: true })

六、使用 mongosh(新版本)

如果你用的是 MongoDB 6+

mongosh

命令与 mongo 基本一致。


如果你有具体场景(如:千万级数据、分片集群、Docker、定时任务),我可以给你更针对性的索引方案。

0 踩