Docs Menu

Docs HomeMongoDB Manual

Single Field Indexes

On this page

  • Compatibility
  • Use Cases
  • Get Started
  • Details

Single field indexes store information from a single field in a collection. By default, all collections have an index on the _id field. 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.

    • A sort order of -1 sorts values in descending order.

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:

Diagram of an index on the ``score`` field (ascending).

In this example, each document in the collection that has a value for the score field is added to the index in ascending order.

You can use single field indexes for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

To learn more about managing indexes for deployments hosted in MongoDB Atlas, see Create, View, Drop, and Hide Indexes.

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. You can create an index on the employee ID field to improve the performance of that query.

To create an index on a single field, see these examples:

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.

←  Index TypesCreate an Index on a Single Field →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.