rmdir.cn

db.collection.createIndex()

创建索引

语法

db.collection.createIndex(<keys>, <options>)

说明

为集合创建索引以提升查询性能。支持单字段索引、复合索引、文本索引、地理空间索引等。1 表示升序,-1 表示降序。

参数

  • keys必填

    索引字段和方向,如 { field: 1 }

  • unique

    true 创建唯一索引

  • sparse

    true 创建稀疏索引(不包含缺失字段的文档)

  • background

    true 后台创建索引(4.2+ 已默认,不再需要)

  • name

    自定义索引名称

示例

创建普通索引

为 email 字段创建升序索引

db.users.createIndex({ email: 1 })

唯一索引

确保 username 唯一

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

复合索引

多字段联合索引

db.orders.createIndex({ userId: 1, createdAt: -1 })

文本索引

创建全文搜索索引

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