Indexes索引
On this page本页内容
Overview概述Query Coverage and Performance查询覆盖率和性能Operational Considerations操作注意事项List Indexes列出索引Index Types索引类型Single Field Indexes单个字段索引Compound Indexes复合索引Multikey Indexes (Indexes on Array Fields)多键索引(数组字段上的索引)Clustered Indexes聚集索引Text Indexes文本索引Geospatial Indexes地理空间索引Unique Indexes唯一索引Search Indexes搜索索引Create a Search Index创建搜索索引List Search Indexes列出搜索索引Update a Search Index更新搜索索引Drop a Search Index删除搜索索引
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, such as 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服务器文档中的索引策略和数据建模与索引。
List Indexes列出索引
You can use the 可以使用listIndexes()
method to list all of the indexes for a collection. listIndexes()
方法列出集合的所有索引。The listIndexes() method takes an optional ListIndexesOptions
parameter.
listIndexes()
方法采用一个可选的
ListIndexesOptions
参数。
The listIndexes()
method returns an object of type ListIndexesCursor.listIndexes()
方法返回一个ListIndexesCursor
类型的对象。
The following code uses the 以下代码使用listIndexes()
method to list all the indexes in a collection:listIndexes()
方法列出集合中的所有索引:
const result = await collection.listIndexes().toArray();
console.log("Existing indexes:\n");
for(const doc in result){
console.log(doc);
}
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 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 = { _id: 0, title: 1 };
const cursor = movies
.find(query)
.sort(sort)
.project(projection);
To learn more, see Single Field Indexes.要了解更多信息,请参阅单字段索引。
Compound Indexes复合索引
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.在“电影”集合中的“type”和“genre”字段上创建一个升序索引。
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 = { _id: 0, type: 1, genre: 1 };
const cursor = movies
.find(query)
.sort(sort)
.project(projection);
To learn more, see Compound Indexes.要了解更多信息,请参阅复合索引。
Multikey Indexes多键索引 (Indexes on Array Fields)(数组字段上的索引)
Multikey indexes are indexes that improve the performance of queries on fields that contain array values.多键索引是用于提高对包含数组值的字段的查询性能的索引。
You can create a multikey index on a field with an array value by calling the 通过调用createIndex()
method. createIndex()
方法,可以在具有数组值的字段上创建多键索引。The following code creates an ascending index on the 以下代码在cast
field in the movies
collection of the sample_mflix
database:sample_mflix
数据库的movies
集合中的cast
字段上创建一个升序索引:
const database = client.db("sample_mflix");
const movies = database.collection("movies");
//Create a multikey index on the "cast" field在“强制转换”字段上创建多键索引
const result = await movies.createIndex({ cast: 1 });
The following code queries the multikey index to find documents with a 以下代码查询多键索引以查找具有包含“Viola Davis”的cast
field value that contains "Viola Davis":cast
字段值的文档:
const query = { cast: "Viola Davis" };
const projection = { _id: 0, cast: 1 , title: 1 };
const cursor = movies
.find(query)
.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 Server manual.有关多键索引的完整解释,包括对其行为和限制的讨论,请参阅MongoDB Server手册中的多键索引页面。
Clustered Indexes聚集索引
Clustered indexes are indexes that improve the performance of insert, update, and delete operations on clustered collections. 聚集索引是提高聚集集合上插入、更新和删除操作性能的索引。Clustered collections store documents ordered by the clustered index key value.聚集集合存储按聚集索引键值排序的文档。
To create a clustered index, specify the 若要创建聚集索引,请在clusteredIndex
option in the CollectionOption
. CollectionOption
中指定clusteredIndex
选项。The clusteredIndex
option must specify the _id
field as the key and the unique field as true
.clusteredIndex
选项必须将_id
字段指定为键,将unique
字段指定为true
。
The following example uses the 以下示例使用createCollection()
method to create a clustered index on the _id
field in the vendors
collection of the tea
database.createCollection()
方法在tea
数据库的vendors
集合中的_id
字段上创建聚集索引。
const db = client.db('tea');
await db.createCollection('ratings', {
clusteredIndex: {
key: { _id: 1 },
unique: true
}
});
To learn more, see Clustered Indexes and Clustered Collections.要了解更多信息,请参阅聚集索引和聚集集合。
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, so you can specify the default language as an option when creating the index. MongoDB支持各种语言的文本搜索,因此您可以在创建索引时指定默认语言作为选项。You can also specify a weight option to prioritize certain text fields in your index. 您还可以指定一个权重选项来对索引中的某些文本字段进行优先级排序。These weights denote the significance of fields relative to the other indexed fields.这些权重表示字段相对于其他索引字段的重要性。
To learn more about text searches, see our guide on text search queries.要了解有关文本搜索的更多信息,请参阅文本搜索查询指南。
The following example uses the 以下示例使用createIndex()
method to perform the following actions:createIndex()
方法执行以下操作:
Create a在text
index on thetitle
andbody
fields in theblogPosts
collectionblogPosts
集合中的title
和body
字段上创建一个文本索引Specify指定english
as the default languageenglish
为默认语言Set the field weight of将body
to10
andtitle
to3
body
的字段权重设置为10
,title
设置为3
const myDB = client.db("testDB");
const myColl = myDB.collection("blogPosts");
//Create a text index on the "title" and "body" fields在“title”和“body”字段上创建文本索引
const result = await myColl.createIndex(
{ title: "text", body: "text" },
{ default_language: "english" },
{ weights: { body: 10, title: 3 } }
);
The following query uses the text index created in the preceding code:以下查询使用在前面的代码中创建的文本索引:
const query = { $text: { $search: "life ahead" } };
const projection = { _id: 0, title: 1 };
const cursor = myColl.find(query).project(projection);
To learn more about text indexes, see Text Indexes in the Server manual.要了解有关文本索引的详细信息,请参阅服务器手册中的文本索引。
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 Point对象,用于描述剧院的坐标:
{
"_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
数据库中的theaters
集合的locationgeo
字段上创建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.在“theaters”集合中的“locationgeo”字段上创建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及更早版本中使用的“遗留坐标对”语法。To learn more, see Geospatial Queries.若要了解更多信息,请参阅地理空间查询。
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.在“剧院”集合中的“剧院ID”字段上创建一个唯一索引。
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
To learn more, see Unique Indexes.要了解更多信息,请参阅唯一索引。
Search Indexes搜索索引
Atlas Search is a feature that allows you to perform full-text searches. Atlas Search是一个允许您执行全文搜索的功能。To learn more, see the Atlas Search documentation.要了解更多信息,请参阅Atlas Search文档。
Before you can perform a search on an Atlas collection, you must first create an Atlas Search index on the collection. 在对Atlas集合执行搜索之前,必须先在集合上创建Atlas搜索索引。An Atlas Search index is a data structure that categorizes data in a searchable format.Atlas Search索引是一种以可搜索格式对数据进行分类的数据结构。
You can use the following methods to manage your Search indexes:您可以使用以下方法来管理搜索索引:
createSearchIndex()
createSearchIndexes()
listSearchIndexes()
updateSearchIndex()
dropSearchIndex()
The following sections provide code samples that use each of the preceding methods to manage Search indexes.以下部分提供了使用前面的每个方法来管理搜索索引的代码示例。
Create a Search Index创建搜索索引
You can use the createSearchIndex()您可以使用 and createSearchIndexes()
methods to create new Search indexes.
createSearchIndex()
和
createSearchIndexes()
方法来创建新的搜索索引。
The following code shows how to use the 以下代码显示如何使用createSearchIndex()
method to create an index called search1
:createSearchIndex()
方法创建一个名为search1
的索引:
const index1 = {
name: "search1",
definition: {
"mappings": {
"dynamic": true
}
}
}
await collection.createSearchIndex(index1);
List Search Indexes列出搜索索引
You can use the listSearchIndexes()可以使用 method to return a cursor that contains the Search indexes of a given collection.
listSearchIndexes()
方法返回一个游标,该游标包含给定集合的搜索索引。
The listSearchIndexes()
method takes an optional string parameter, name
, to return only the indexes with matching names. listSearchIndexes()
方法采用可选的字符串参数name
,只返回名称匹配的索引。It also takes an optional aggregateOptions它还采用了一个可选的 parameter.
aggregateOptions
参数。
The following code uses the 以下代码使用listSearchIndexes()
method to list the Search indexes in a collection:listSearchIndexes()
方法列出集合中的搜索索引:
const result = await collection.listSearchIndexes().toArray();
console.log("Existing search indexes:\n");
for (const doc in result) {
console.log(doc);
}
Update a Search Index更新搜索索引
You can use the updateSearchIndex()您可以使用 method to update a Search index.
updateSearchIndex()
方法来更新搜索索引。
The following code shows how to use the 以下代码显示如何使用updateSearchIndex()
method to update an index called search1
to specify a string type for the description
field:updateSearchIndex()
方法更新名为search1
的索引,以指定description
字段的字符串类型:
const index2 = {
"mappings": {
"dynamic": true,
"fields": {
"description": {
"type": "string"
}
}
}
}
await collection.updateSearchIndex("search1", index2);
Drop a Search Index删除搜索索引
You can use the dropSearchIndex()可以使用 method to remove a Search index.
dropSearchIndex()
方法删除搜索索引。
The following code shows how to use the 以下代码显示如何使用dropSearchIndex()
method to remove an index called search1
:dropSearchIndex()
方法删除名为search1
的索引:
await collection.dropSearchIndex("search1");