Guide to single and compound index creation in Mongo

Vipul Kumar
3 min readNov 23, 2023

--

In MongoDB, an index is a data structure that improves the speed of data retrieval operations on a database. Indexes are crucial for optimizing query performance, as they enable the database engine to quickly narrow down the search space and locate the relevant documents without scanning the entire collection. While indexes significantly enhance query speed, it’s essential to carefully design and manage them, considering factors such as the types of queries your application performs, the size of the dataset, and the overall system performance goals. Efficient use of indexes is a key aspect of MongoDB’s flexibility and scalability, contributing to its effectiveness in handling diverse data structures and workloads.

Last week, I encountered an issue, while creating an index for a single field as well as a compound index. So, below is the documented steps for creating index using annotations.

Index in Mongo:

Automatic index creation is turned OFF by default now.

To turn automatic index creation ON please override autoIndexCreation() in your configuration.

package com.mycompany.domain;

@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {

@Override
public boolean autoIndexCreation() {
return true;
}
}

Index creation:

Default

_id is an ObjectId object, 12-byte BSON type that guarantees uniqueness within the collection. The ObjectId is generated based on timestamp, machine ID, process ID, and a process-local incremental counter.

Single Field

To create an index on a single field, you typically employ the @Indexed annotation in your data model class. This annotation is defined on individual properties.

For instance, consider a scenario where you want to create an index on a "clickedOn" field to expedite queries related to clicked data information. You would annotate the "clickedOn" field in your MongoDB document class as follows:

package com.mycompany.domain;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document("Clicks")
public class Clicks {

@Id
private String id;
@Indexed(unique = true)
private String clickedOn;

}

In this example, the @Indexed annotation, with the optional unique = true parameter, not only creates an index on the "clickedOn" field but also ensures the uniqueness of values in that field. This can significantly enhance query performance when searching for documents based on the indexed field. Once the annotated class is in place, MongoDB will automatically create the specified index when documents are inserted or updated.

Compound Field / Compound Index

Compound indexes are also supported. They are defined at the class level, rather than on individual properties. Below is the example of creating compound index of lastName in ascending order and age in descending order:

package com.mycompany.domain;

@Document
@CompoundIndex(name = "_lastName_1_age_-1", def = "{'lastName': 1, 'age': -1}")
public class Person {

@Id
private ObjectId id;
private Integer age;
private String firstName;
private String lastName;

}

Note: @CompoundIndex is repeatable using @CompoundIndexes as its container.


package com.mycompany.domain;

@Document
@CompoundIndexes({
@CompoundIndex(name = "_firstName_age_-1", def = "{'firstName' : 1, 'age': 1}"),
@CompoundIndex(name = "_lastName_1_age_-1", def = "{'lastName': 1, 'age': -1}")
})
public class Person {

@Id
private ObjectId id;
private Integer age;
private String firstName;
private String lastName;

}

Conclude:

Following steps mentioned above, you can create index on single field as well as on compound fields.

Happy learning… keep smiling…

--

--

Vipul Kumar
Vipul Kumar

Written by Vipul Kumar

Transforming complexity into elegant solutions, one line at a time.

No responses yet