Skip to main content

Compound Indexes

A compound index in MongoDB is an index that is created on multiple fields in a collection. It allows queries that involve multiple fields to be executed more efficiently. A compound index can significantly improve query performance in cases where you have a large dataset and frequently run queries that involve multiple fields.

To create a compound index, you can use the createIndex() method of a MongoDB collection. Here is an example of creating a compound index on two fields (field1 and field2) in a collection:

db.collection("myCollection").createIndex({ field1: 1, field2: 1 }, function(err, result) {
console.log("Compound index created");
});

In the example above, we create a compound index on field1 and field2. The 1 value in the index definition indicates that the index should be created in ascending order. You can also use -1 to create an index in descending order.

When a query is executed that involves both fields, MongoDB can use the compound index to quickly locate the relevant documents. For example, the following query will use the compound index to find all documents where field1 equals "value1" and field2 equals "value2":

db.collection("myCollection").find({ field1: "value1", field2: "value2" }).toArray(function(err, result) {
console.log("Found documents: " + JSON.stringify(result));
});

In addition to improving query performance, compound indexes can also help reduce the amount of disk space required to store index data. When you create a compound index, MongoDB will store a single index entry for each unique combination of values in the indexed fields, rather than storing separate index entries for each field.

It is important to note that while compound indexes can improve query performance, they can also have a negative impact on insert and update performance, as MongoDB must update the index for each affected document. Therefore, it is important to carefully consider the balance between query performance and insert/update performance when deciding whether to create a compound index.