Indexes索引¶
On this page
Overview概述¶
Indexes are data structures that support the efficient execution of queries in MongoDB. 索引是支持在MongoDB中高效执行查询的数据结构。They contain copies of parts of the data in documents to make queries more efficient.它们包含文档中部分数据的副本,以提高查询效率。
Without indexes, MongoDB must scan every document in a collection to find the documents that match each query. 如果没有索引,MongoDB必须扫描集合中的每个文档,以找到与每个查询匹配的文档。These collection scans are slow and can negatively affect the performance of your application. 这些收集扫描速度慢,可能会对应用程序的性能产生负面影响。By using an index to limit the number of documents MongoDB scans, queries can be more efficient and therefore return faster.通过使用索引限制MongoDB扫描的文档数量,查询可以更高效,因此返回速度更快。
Query Coverage and Performance查询覆盖率和性能¶
When you execute a query against MongoDB, your query can include three parts:对MongoDB执行查询时,查询可以包括三个部分:
query criteria that specify field(s) and value(s) you are looking for指定要查找的字段和值的查询条件options that affect the query's execution (e.g. read concern)影响查询执行的选项(例如,读取关注点)projection criteria to specify the fields MongoDB should return (optional)用于指定MongoDB应返回的字段的投影条件(可选)
When all the fields specified in the query criteria and projection of a query are indexed, MongoDB returns results directly from the index without scanning any documents in the collection or loading them into memory.当查询条件和查询投影中指定的所有字段都被索引时,MongoDB直接从索引返回结果,而无需扫描集合中的任何文档或将其加载到内存中。
For additional information on how to ensure your index covers your query criteria and projection, see the MongoDB manual articles on query coverage and index intersection.有关如何确保索引覆盖查询条件和投影的更多信息,请参阅MongoDB手册中有关查询覆盖率和索引交叉点的文章。
Operational Considerations业务考虑¶
To improve query performance, build indexes on fields that appear often in your application's queries and operations that return sorted results. 要提高查询性能,请在应用程序查询和返回排序结果的操作中经常出现的字段上构建索引。Each index that you add consumes disk space and memory when active so you should track index memory and disk usage for capacity planning. 您添加的每个索引在活动时都会消耗磁盘空间和内存,因此您应该跟踪索引内存和磁盘使用情况以进行容量规划。In addition, when a write operation updates an indexed field, MongoDB also has to update the related index.此外,当写入操作更新索引字段时,MongoDB还必须更新相关索引。
For more information on designing your data model and choosing indexes appropriate for your application, see the MongoDB server documentation on Indexing Strategies and Data Modeling and Indexes.有关设计数据模型和选择适合应用程序的索引的更多信息,请参阅MongoDB服务器文档中有关索引策略和数据建模与索引的内容。
Index Types索引类型¶
MongoDB supports a number of different index types to support querying your data. MongoDB支持多种不同的索引类型来支持查询数据。The following sections describe the most common index types and provide sample code for creating each index type.以下各节介绍了最常见的索引类型,并提供了创建每种索引类型的示例代码。
Single Field and Compound Indexes单字段和复合索引¶
Single field indexes单字段索引 are indexes that improve performance for queries that specify ascending or descending sort order on a single field of a document.对于指定文档单个字段的升序或降序排序顺序的查询,索引可以提高性能。
The following example uses the 下面的示例使用createIndex()
method to create an ascending order index on the title
field in the movies
collection in the sample_mflix
database.createIndex()
方法在sample_mflix
数据库的movies
集合中的title
字段上创建升序索引。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create an ascending index on the "title" field in the
// "movies" collection.
const result = await movies.createIndex({ title: 1 });
console.log(`Index created:${result}`);
The following is an example of a query that would be covered by the index created above.下面是上面创建的索引将涵盖的查询示例。
const query = { title: "Batman" }
const sort = { title: 1 };
const projection = { title: 1 };
const cursor = movies
.find(query)
.sort(sort)
.project(projection);
See the MongoDB server manual section on single field indexes for more information.有关更多信息,请参阅MongoDB服务器手册中关于单字段索引的部分。
Compound indexes复合索引 are indexes that improve performance for queries that specify ascending or descending sort order for multiple fields of a document. 用于提高查询性能的索引,这些查询为文档的多个字段指定升序或降序排序顺序。You must specify the direction (ascending or descending) for each field in the index.必须为索引中的每个字段指定方向(升序或降序)。
The following example uses the 下面的示例使用createIndex()
method to create a compound index on the type
and genre
fields in the movies
collection in the sample_mflix
database.createIndex()
方法在sample_mflix
数据库的movies
集合中的type
和genre
字段上创建复合索引。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create an ascending index on the "type" and "genre" fields
// in the "movies" collection.
const result = await movies.createIndex({ type: 1, genre: 1 });
console.log(`Index created:${result}`);
The following is an example of a query that would be covered by the index created above.下面是上面创建的索引将涵盖的查询示例。
const query = { type: "movie", genre: "Drama" };
const sort = { type: 1, genre: 1 };
const projection = { type: 1, genre: 1 };
const cursor = movies
.find(query)
.sort(sort)
.project(projection);
See the MongoDB server manual section on Compound indexes for more information.有关更多信息,请参阅MongoDB服务器手册中关于复合索引的部分。
Multikey Indexes (Indexes on Array Fields)多键索引(数组字段上的索引)¶
Multikey indexes多键索引 are indexes that improve performance for queries that specify ascending or descending indexes on fields that contain an array value. 对于在包含数组值的字段上指定升序或降序索引的查询,索引可以提高性能。You can define a multikey index using the same syntax as a single field or compound index.可以使用与单个字段或复合索引相同的语法定义多键索引。
The following example use the 下面的示例使用createIndex()
method to create an ascending index on the cast
field (array of names) in the movies
collection in the sample_mflix
database.createIndex()
方法在sample_mflix
数据库的movies
集合中的cast
字段(名称数组)上创建升序索引。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a multikey index on the "cast" array field
// in the "movies" collection.
const result = await movies.createIndex({ cast: 1 });
console.log(`Index created:${result}`);
The following is an example of a query that would be covered by the index created above.下面是上面创建的索引将涵盖的查询示例。
const query = { cast: "Burt Reynolds" };
const sort = { cast: 1, genre: 1 };
const projection = { cast: 1 };
const cursor = movies
.find(query)
.sort(sort)
.project(projection);
Multikey indexes behave differently from non-multikey indexes in terms of query coverage, index bound computation, and sort behavior. 在查询覆盖率、索引边界计算和排序行为方面,多键索引的行为与非多键索引不同。For a full explanation of multikey indexes, including a discussion of their behavior and limitations, refer to the Multikey Indexes page in the MongoDB manual.有关多键索引的完整解释,包括对其行为和限制的讨论,请参阅MongoDB手册中的多键索引页面。
Text Indexes文本索引¶
Text indexes support text search queries on string content. 文本索引支持对字符串内容的文本搜索查询。These indexes can include any field whose value is a string or an array of string elements. 这些索引可以包括值为字符串或字符串元素数组的任何字段。MongoDB supports text search for various languages. MongoDB支持各种语言的文本搜索。You can specify the default language as an option when creating the index. 创建索引时,可以指定默认语言作为选项。Read our guide on text search queries for more information.有关更多信息,请阅读我们的文本搜索查询指南。
The following example uses the 以下示例使用createIndex()
method to create a text
index on the fullplot
field in the movies
collection in the sample_mflix
database and specifies english
as the default language.createIndex()
方法在sample_mflix
数据库的movies
集合中的fullplot
字段上创建text
索引,并将english
指定为默认语言。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a text index on the "fullplot" field in the
// "movies" collection.
const result = await movies.createIndex({ fullplot: "text" }, { default_language: "english" });
console.log(`Index created:${result}`);
The following is an example of a query that would be covered by the index created above. 下面是上面创建的索引将涵盖的查询示例。Note that the 请注意,由于文本索引不包含排序顺序,因此省略了sort
is omitted because text indexes do not contain sort order.sort
。
const query = { $text: { $search: "java coffee shop" } };
const projection = { fullplot: 1 };
const cursor = movies
.find(query)
.project(projection);
For a full explanation of text search with MongoDB, refer to Text Indexes in the MongoDB manual.有关使用MongoDB进行文本搜索的完整说明,请参阅MongoDB手册中的文本索引。
Geospatial Indexes地理空间索引¶
MongoDB supports queries of geospatial coordinate data using 2dsphere indexes. MongoDB支持使用2dsphere索引查询地理空间坐标数据。With a 2dsphere index, you can query the geospatial data for inclusion, intersection, and proximity. 使用2dsphere索引,可以查询地理空间数据的包含、相交和邻近性。For more information on querying geospatial data with the MongoDB Node.js driver, read our Search Geospatial guide.有关使用MongoDB Node.js驱动程序查询地理空间数据的更多信息,请阅读《搜索地理空间指南》。
To create a 2dsphere index, you must specify a field that contains only GeoJSON objects. 要创建2dsphere索引,必须指定仅包含GeoJSON对象的字段。For more details on this type, see the MongoDB server manual page on GeoJSON objects.有关此类型的更多详细信息,请参阅GeoJSON对象上的MongoDB服务器手册页面。
The location.geo
field in following sample document from the theaters
collection in the sample_mflix
database is a GeoJSON Point object that describes the coordinates of the theater:sample_mflix
数据库中theaters
集合的以下示例文档中的location.geo
字段是描述剧院坐标的GeoJSON点对象:
{
"_id" : ObjectId("59a47286cfa9a3a73e51e75c"),
"theaterId" : 104,
"location" : {
"address" : {
"street1" : "5000 W 147th St",
"city" : "Hawthorne",
"state" : "CA",
"zipcode" : "90250"
},
"geo" : {
"type" : "Point",
"coordinates" : [
-118.36559,
33.897167
]
}
}
}
The following example uses the 以下示例使用createIndexes()
method to create a 2dsphere
index on the location.geo
field in the theaters
collection in the sample_mflix
database to enable geospatial searches.createIndexes()
方法在sample_mflix
数据库中剧院集合的location.geo
字段上创建2dsphere
索引,以启用地理空间搜索。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a 2dsphere index on the "location.geo" field in the "theaters" collection.在“剧院”集合的“location.geo”字段上创建一个2dsphere索引。
const result = await movies.createIndex({ "location.geo": "2dsphere" });
console.log(`Index created:${result}`);
MongoDB also supports MongoDB还支持2d
indexes for calculating distances on a Euclidean plane and for working with the "legacy coordinate pairs" syntax used in MongoDB 2.2 and earlier. 2d
索引,用于计算欧几里德平面上的距离,以及使用MongoDB 2.2及更早版本中使用的“传统坐标对”语法。See the Geospatial Queries page in the MongoDB server manual for more further information.有关更多信息,请参阅MongoDB服务器手册中的地理空间查询页面。
Unique Indexes唯一索引¶
Unique indexes ensure that the indexed fields do not store duplicate values. 唯一索引确保索引字段不存储重复的值。By default, MongoDB creates a unique index on the 默认情况下,MongoDB在创建集合期间在_id
field during the creation of a collection. _id
字段上创建唯一索引。To create a unique index, specify the field or combination of fields that you want to prevent duplication on and set the 要创建唯一索引,请指定要防止重复的字段或字段组合,并将unique
option to true
.unique
选项设置为true
。
The following example uses the 以下示例使用createIndex()
method to create a unique index on the theaterId
field in the theaters
collection of the sample_mflix
database.createIndex()
方法在sample_mflix
数据库的theaters
集合中的theaterId
字段上创建唯一索引。
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create a unique index on the "theaterId" field in the "theaters" collection.
const result = await movies.createIndex({ theaterId: 1 }, { unique: true });
console.log(`Index created:${result}`);
If you attempt to perform a write operation that stores a duplicate value that violates the unique index, MongoDB will throw an error that resembles the following:如果您试图执行一个写入操作,该操作存储了一个违反唯一索引的重复值,MongoDB将抛出一个类似以下的错误:
E11000 duplicate key error index
Refer to the Unique Indexes page in the MongoDB server manual for more information.有关更多信息,请参阅MongoDB服务器手册中的唯一索引页面。