Navigation
This version of the documentation is archived and no longer supported.

Create a Compound Index

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.ensureIndex( { 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.ensureIndex( { 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.