mongodb 创建索引

阅读:48
作者:majingjing
发布:2025-04-19 20:55:17

基本语法

db.collectionName.createIndex(keys, options)

  • collectionName:你要在其上创建索引的集合名称。
  • keys:一个文档,指定了要索引的字段及其排序顺序(1 表示升序,-1 表示降序)。
  • options:可选参数,用于指定索引的其他属性,如唯一性、名称等。

示例

1. 创建单字段索引

假设我们有一个名为 users 的集合,并且我们希望在这个集合的 email 字段上创建一个升序索引。

db.users.createIndex({ email: 1 });
2. 创建唯一索引

如果我们希望 email 字段是唯一的,可以添加 unique: true 选项。

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

3. 创建复合索引

复合索引是在多个字段上创建的索引。例如,在 users 集合的 firstName 和 lastName 字段上创建一个复合索引。

db.users.createIndex({ firstName: 1, lastName: 1 });
4. 创建降序索引

如果你想在某个字段上创建降序索引,可以将排序顺序设置为 -1。

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

5. 创建文本索引

文本索引用于支持全文搜索。假设我们有一个 articles 集合,并且我们希望在 content 字段上创建一个文本索引。

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

6. 创建多键索引

多键索引用于支持数组字段的索引。假设我们有一个 products 集合,并且我们希望在 tags 数组字段上创建一个索引。

db.products.createIndex({ tags: 1 });

注意事项

索引名称:默认情况下,MongoDB 会自动生成索引名称。你也可以通过 name 选项指定自定义的索引名称。

  db.users.createIndex({ email: 1 }, { unique: true, name: "emailIndex" });
  
  • 索引大小:MongoDB 对索引大小有限制,单个索引文档不能超过 1024 字节。如果需要索引大字段,可以考虑使用文本索引或其他解决方案。
  • 性能影响:创建索引可以显著提高查询性能,但也会增加写操作的开销。因此,在创建索引时需要权衡查询性能和写操作性能。