MongoDB Compound Indexes (original) (raw)

Last Updated : 5 May, 2026

MongoDB compound indexes combine multiple fields in a single structure to speed up queries that filter or sort on more than one field, improving query performance.

Create a Compound Index

In MongoDB, we can create a compound index using the createIndex() method.

**Syntax:

db.collection.createIndex({: , : , ...})

Examples of Compound Indexes

In the following examples, we are working with:

Screenshot-2026-02-19-104148

Example 1: Creating a compound index on manufacture and price

Creating an index on manufacturer in ascending order and then on price in descending order.

db.products.createIndex({manufacturer:1, price:-1})

**Output:

Screenshot-2026-02-19-104912

Example 2: Creating a compound index on product, manufacturer, and price

Creating an index on the product in ascending order then it will be sorted for the manufacturer in ascending order, and then it will again be sorted for price

**Query:

db.products.createIndex({product:1,manufacturer:1,price:1})

**Output:

Screenshot-2026-02-19-104713

Sorting using Compound Indexes

MongoDB can use indexes to efficiently perform sorting when the sort keys match an index prefix.

The created index can be used for sorting on the following prefixes -

Example Prefix
db.data.find().sort({a: 1}) {a: 1}
db.data.find().sort({a: -1}) {a: 1}
db.data.find().sort({a: 1, b: -1}) {a: 1, b: -1}
db.data.find().sort({a: -1, b: 1}) {a: 1, b: -1}
db.data.find().sort({a: 1, b: -1, c: 1}) {a: 1, b: -1, c: 1}

**Example: Fixes the prefix field and sorts using the remaining indexed fields.

Consider the following data for the query.

Screenshot-2026-02-19-112643

**Create Index first.

db.products.createIndex({ manufacturer: 1, price: -1, rating: 1 })

**Then,

db.products.find({ manufacturer: "lays" }).sort({ price: -1, rating: 1 })

**Output:

Screenshot-2026-02-19-114654