对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

索引

在本指南中,您可以了解如何使用 Rust 驱动程序创建和管理索引。索引是 MongoDB 中用于提高查询性能的特殊数据结构。

如果在没有任何索引的集合上执行查询,MongoDB 会扫描每个文档以查找匹配项。这些集合扫描很慢,可能会对应用程序的性能产生负面影响。当您创建涵盖查询的索引时,MongoDB 会限制其检查以查找匹配项的文档数量,从而提高性能。

提示

You can use indexes in update operations, delete operations, and some aggregation pipeline stages. To learn more about using indexes in aggregations, see Improve Performance with Indexes and Document Filters in the Server manual.

下表描述了可以包含在 MongoDB 查询中的元素:

元素
说明

查询

必需
指定要匹配的字段和值

选项

Optional
指定查询的执行方式

投射

Optional
指定 MongoDB 在匹配文档中返回的字段

Sort

Optional
指定返回文档的顺序

当查询元素引用全部包含在同一索引中的字段时,MongoDB 可以直接从索引返回结果。 这些查询称为覆盖查询。

To learn how to ensure that your index covers your query, see Covered Query in the Server manual.

重要

排序条件

您的排序条件必须与索引的顺序一致或相反。

假设一个collection在name字段上具有以下索引(按升序 (AZ) 排列),在age字段上具有以下索引(按降序排列 (9-0)):

name_1_age_-1

当您采用以下任一配置对文档进行排序时,MongoDB 会使用此索引:

  • name 升序, age降序

  • name 降序,age 升序

如果为两个字段指定相同的排序顺序,则 MongoDB 不使用索引,而是执行内存中排序。

要提高查询性能,请为查询中经常出现的字段创建索引。 但是,追踪索引内存和磁盘使用情况以进行容量规划是一个好习惯,因为每个索引都会消耗磁盘空间和内存。此外,如果写入操作更新了索引字段,MongoDB 还必须更新相关索引。

MongoDB supports dynamic schemas, so your application can query against fields with unknown or variable names. If you are connected to MongoDB Server version 4.2 or later, you can create wildcard indexes to support these queries. To learn more about this index type, see Wildcard Indexes in the Server manual.

MongoDB 支持多种索引类型来支持您的查询。 以下部分介绍了常见的索引类型,并展示了如何在集合中创建每种索引类型。

注意

样本集合

The examples in this guide use collections from the Atlas sample data. To learn how to import this data, see the Load Sample Data tutorial in the Atlas documentation.

您可以使用create_index()和create_indexes()方法在collection中创建索引。create_index()方法接受一个IndexModel结构体参数,您可以使用该类型的builder()方法来构造该参数。

要查看索引类型的完整列表,请参阅 MongoDB Server手册中的 索引类型 。

单个字段索引包含对文档字段的引用。

该索引提高了单字段查询和排序的性能。 它还支持TTL索引,可在一定时间后自动从集合删除文档。 要学习;了解有关TTL索引的更多信息,请参阅服务器手册中的TTL索引。

When you create a new collection, MongoDB automatically creates a unique, single field index on the _id field.

以下代码在sample_training.zips collection中的city字段上创建一个升序索引:

let index = IndexModel::builder().keys(doc! { "city": 1 }).build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

复合索引包含对多个文档字段的引用。

该索引提高了对多个字段进行查询和排序的性能。 创建复合索引时,必须为每个索引字段指定一个方向。

您可以使用与创建单字段索引相同的语法来创建多键索引。

以下代码在sample_training.zips collection 中的city和pop 字段 上创建复合索引:

let index = IndexModel::builder()
.keys(doc! { "city": 1, "pop": -1 })
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

多键索引包含对数组值字段的引用。此索引提高了对数组字段的查询性能。

您可以使用与创建单字段索引相同的语法来创建多键索引。

tagssample_training.posts以下代码在collection中的 字段上创建多键索引:

let index = IndexModel::builder().keys(doc! { "tags": 1 }).build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

聚集索引可提高对聚集集合的插入、更新和删除操作的性能。聚集集合按聚集索引键值的顺序存储文档。要了解有关这些集合的更多信息,请参阅服务器手册中的聚集集合。

只有在创建collection时才能创建集群化索引。要创建集群化集合,请执行以下步骤:

  1. 创建一个ClusteredIndex实例。

  2. 将ClusteredIndex 实例设置为 实例的clustered_index CreateCollectionOptions字段的值。

  3. 将选项传递给create_collection()方法。

您必须设置ClusteredIndex结构的以下字段:

  • key字段,用于指定密钥模式。此字段的值必须是{ _id: 1 } 。

  • unique字段,指定索引的唯一性。 此字段的值必须是true 。

ClusteredIndex要创建自动使用所需值的实例,您可以调用该类型的default() 方法。

以下代码在数据库sample_training中创建名为collectionitems的新集合时,在字段_id上创建具有默认配置的集群索引:

let db = client.database("sample_training");
let cl_idx = ClusteredIndex::default();
let opts = CreateCollectionOptions::builder()
.clustered_index(cl_idx)
.build();
db.create_collection("items", opts).await?;

文本索引支持对字符串内容进行文本查询。 该索引引用具有字符串值或字符串大量值的字段。 MongoDB支持多种语言的文本查询。创建文本索引时,可以指定默认语言作为选项。

A collection can only contain one text index. To create a text index on multiple text fields, you can create a compound index. When you run a text query after creating a compound index, the search operation runs on all the text fields in the compound index.

提示

文本索引与MongoDB搜索索引

Text indexes are different from MongoDB Search indexes, which enable full-text searches. To learn more about MongoDB Search indexes, see the MongoDB Search Quick Start.

bodysample_training.posts以下代码在collection集合中的字段字段上创建文本索引。该代码设置一个选项以将"spanish"指定为文本索引的默认语言:

let idx_opts = IndexOptions::builder()
.default_language("spanish".to_string())
.build();
let index = IndexModel::builder()
.keys(doc! { "body": "text" })
.options(idx_opts)
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

MongoDB 通过使用2dsphere索引支持包含地理空间坐标数据的查询。 您可以使用 GeoJSON 对象值在字段上创建2dsphere索引。

此索引类型支持以下任务:

  • 查询地理空间数据以查找包含项、交集和邻近范围

  • 欧几里得平面上的距离计算

重要

不能对同一字段创建两个地理空间索引。

sample_mflix.theaters集合中的以下示例文档包含字段location.geo 。 该字段具有 GeoJSON point 值:

{
"_id": ...,
"theaterId": ...,
"location": {
"address": ...,
"geo": {
"type": "Point",
"coordinates": [
-93.24565,
44.85466
]
}
}
}

以下代码在collection中的字段 上创建地理空间2dsphere 索引:location.geosample_mflix.theaters

let index = IndexModel::builder()
.keys(doc! { "location.geo": "2dsphere" })
.build();
let idx = my_coll.create_index(index, None).await?;
println!("Created index:\n{}", idx.index_name);

唯一索引可确保索引字段不存储重复值。 默认,当您创建collection时,MongoDB 会在_id字段上创建唯一的单字段索引。

要创建唯一索引,请指定要保持唯一性的字段或字段组合,并将 unique 选项设置为 true。

以下代码演示如何在IndexOptions实例中将unique字段设置为true ,并在创建IndexModel时传递这些选项:

let opts = IndexOptions::builder().unique(true).build();
let index = IndexModel::builder()
.keys(doc! { "_id": -1 })
.options(opts)
.build();

您可以删除collection中除_id字段上的默认唯一索引之外的任何索引。要删除索引,请将索引的名称传递给drop_index()方法。

提示

删除所有索引

您可以使用drop_indexes()方法一次性删除collection上除_id索引之外的所有索引。

city_1sample_training.zips以下示例从collection中删除名为 的索引:

my_coll.drop_index("city_1".to_string(), None).await?;

To learn more about designing data models and creating appropriate indexes for your application, see Indexing Strategies and Create Indexes to Support Your Queries in the Server manual.

要学习;了解有关执行读取操作的更多信息,请参阅读取操作部分中的指南。

要了解有关本指南中提到的概念的更多信息,请参阅以下服务器文档:

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档: