For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Indexes for Query Optimization

In this guide, you can learn how to use the MongoDB Extension for Hibernate ORM to declare single-field, compound, and unique indexes on an entity. The Hibernate ORM extension translates the indexes and unique constraints you declare on your entities into MongoDB index operations when you enable schema generation.

To create the indexes and unique constraints declared on your entities, enable schema generation in your application's configuration. You can enable schema generation with either the create or create-drop action:

  • create: Creates the schema objects without dropping them when the SessionFactory closes.

  • create-drop: Creates the schema objects when the SessionFactory opens and drops them when it closes.

Warning

The create-drop action is intended for development and testing. Do not use it when you need to preserve production data.

If you use Spring Boot, add the following property to your application.properties file:

spring.jpa.properties.jakarta.persistence.schema-generation.database.action=create-drop

If you configure Jakarta Persistence directly, add the following property to your persistence.xml file:

<property name="jakarta.persistence.schema-generation.database.action"
value="create-drop"/>

Alternatively, you can set the property in your hibernate.properties file:

jakarta.persistence.schema-generation.database.action=create-drop

When schema generation runs, the Hibernate ORM extension creates the collection and issues MongoDB createIndexes commands for the indexes and unique constraints that your entities declare.

The examples in this guide declare indexes and unique constraints by adding @Index and @UniqueConstraint annotations to the @Table annotation of the following Movie entity:

@Entity
@Table(name = "movies")
public class Movie {
@Id
@ObjectIdGenerator
private ObjectId id;
private String title;
private String plot;
private int year;
private List<String> cast;
private List<String> directors;
public Movie(String title, String plot, int year, List<String> cast, List<String> directors) {
this.title = title;
this.plot = plot;
this.year = year;
this.cast = cast;
this.directors = directors;
}
public Movie() {
}
// Getter and setter methods
}

Single field indexes are indexes with a reference to a single field within a collection's documents. They improve query and sort performance for a single field.

The following example creates a single field index in descending order on the year field:

@Table(
name = "movies",
indexes = {
@Index(name = "idx_year", columnList = "year desc")
})

Set the columnList to the field name, and add asc or desc to specify the direction. If you omit the direction, MongoDB creates an ascending index. The name element specifies the name of the MongoDB index.

For more information, see Single Field Indexes in the MongoDB Server manual.

Compound indexes hold references to multiple fields within a collection's documents, improving query and sort performance.

The following example creates a compound index on the title and year fields in descending order:

@Table(
name = "movies",
indexes = {
@Index(name = "idx_title_year", columnList = "title desc,year desc")
})

The order of the fields in the columnList determines the order in which MongoDB sorts the index keys, which affects which query prefixes the index can support. For example, an index on title followed by year can support queries that match title alone, while an index on year does not help a query that matches only title.

For more information, see Compound Indexes in the MongoDB Server manual.

Unique indexes ensure that the indexed fields do not store duplicate values.

You can create a unique index with either the @Index or the @UniqueConstraint annotation:

  • Use @Index(unique = true) when you need to specify index options such as field direction.

  • Use @UniqueConstraint when you want to use the table-level constraint model. The fields in columnNames define the key order, and @UniqueConstraint does not specify field directions, so the resulting unique index is ascending.

The following example creates a unique index on the title field:

@Table(
name = "movies",
indexes = {
@Index(name = "idx_title", columnList = "title", unique = true)
})

The following example creates a unique constraint on the title and plot fields:

@Table(
name = "movies",
uniqueConstraints = {
@UniqueConstraint(name = "uk_title_plot", columnNames = {"title", "plot"})
})

MongoDB treats a null or missing value for an indexed field as an indexed value. Because of the unique constraint, a single-field unique index can contain only one document with a null value in its index entry.

Important

Unique Index Creation Can Fail

MongoDB cannot create a unique index on the specified field or fields if the collection already contains documents with duplicate values for those fields. Review your existing data for duplicate values before creating a unique index.

For more information, see Unique Indexes in the MongoDB Server manual.

To learn more about creating entities and mapping embedded data, see the Create Entities to Represent Collections guide.

To learn how to use your entities to run database operations, see the Perform CRUD Operations and Specify a Query guides.

To view a list of the index types that the Hibernate ORM extension supports, see the Feature Compatibility page.

To learn more about the Jakarta Persistence annotations used in this guide, see the Jakarta Persistence API documentation.