Docs Home → Develop Applications → MongoDB Manual
Single Field Indexes单个字段索引
On this page本页内容
Single field indexes store information from a single field in a collection. 单字段索引存储集合中单个字段的信息。By default, all collections have an index on the _id field. 默认情况下,所有集合在_id
字段上都有一个索引。You can add additional indexes to speed up important queries and operations.您可以添加额外的索引来加快重要的查询和操作。
You can create a single-field index on any field in a document, including:您可以在文档中的任何字段上创建单个字段索引,包括:
Top-level document fields顶级文档字段Embedded documents嵌入的文档Fields within embedded documents嵌入文档中的字段
When you create an index, you specify:创建索引时,可以指定:
The field on which to create the index.要在其上创建索引的字段。The sort order for the indexed values (ascending or descending).索引值的排序顺序(升序或降序)。A sort order of排序顺序1
sorts values in ascending order.1
按升序对值进行排序。A sort order of排序顺序-1
sorts values in descending order.-1
按降序对值进行排序。
To create a single-field index, use the following prototype:要创建单个字段索引,请使用以下原型:
db.<collection>.createIndex( { <field>: <sortOrder> } )
This image shows an ascending index on a single field, 此图显示单个字段的升序索引,score
:score
:
In this example, each document in the collection that has a value for the 在本例中,集合中每个具有score
field is added to the index in ascending order.score
字段值的文档都将按升序添加到索引中。
Use Cases使用案例
If your application repeatedly runs queries on the same field, you can create an index on that field to improve performance. 如果应用程序在同一字段上重复运行查询,则可以在该字段上创建索引以提高性能。For example, your human resources department often needs to look up employees by employee ID. 例如,您的人力资源部门通常需要根据员工ID查找员工。You can create an index on the employee ID field to improve the performance of that query.您可以在“员工ID”字段上创建索引,以提高该查询的性能。
Get Started开始
To create an index on a single field, see these examples:要在单个字段上创建索引,请参阅以下示例:
Details详细信息
For a single-field index, the sort order (ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction.对于单个字段索引,索引键的排序顺序(升序或降序)无关紧要,因为MongoDB可以在任意方向遍历索引。