![]() |
VOOZH | about |
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.
In MongoDB, we can create a compound index using the createIndex() method.
Syntax:
db.collection.createIndex({<field1>: <type1>, <field2>: <type2>, ...})In the following examples, we are working with:
Creating an index on manufacturer in ascending order and then on price in descending order.
db.products.createIndex({manufacturer:1, price:-1})Output:
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:
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.
Create Index first.
db.products.createIndex({ manufacturer: 1, price: -1, rating: 1 })Then,
db.products.find({ manufacturer: "lays" }).sort({ price: -1, rating: 1 })Output: