- Indexes >
- Indexing Tutorials >
- Index Creation Tutorials >
- Create a Compound Index
Create a Compound Index¶
On this page
Indexes allow MongoDB to process and fulfill queries quickly by creating small and efficient representations of the documents in a collection. MongoDB supports indexes that include content on a single field, as well as compound indexes that include content from multiple fields. Continue reading for instructions and examples of building a compound index.
Build a Compound Index¶
To create a compound index use an operation that resembles the following prototype:
db.collection.createIndex( { a: 1, b: 1, c: 1 } )
The value of the field in the index specification describes the kind of index for that field. For example, a value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that orders items in descending order. For additional index types, see Index Types.
Example¶
The following operation will create an index on the item, category, and price fields of the products collection:
db.products.createIndex( { item: 1, category: 1, price: 1 } )
Additional Considerations¶
If your collection holds a large amount of data, and your application needs to be able to access the data while building the index, consider building the index in the background, as described in Background Construction. To build indexes on replica sets, see the Build Indexes on Replica Sets section for more information.
Note
To build or rebuild indexes for a replica set see Build Indexes on Replica Sets.
Some drivers may specify indexes, using NumberLong(1) rather than 1 as the specification. This does not have any affect on the resulting index.
See also
Create an Index, Indexing Tutorials and Index Concepts for more information.
Thank you for your feedback!
We're sorry! You can Report a Problem to help us improve this page.