In addition to supporting queries that match on all the index fields, compound indexes can support queries that match on the prefix of the index fields. For details, see Prefixes (page 490). 

## Sort Order 

Indexes store references to fields in either ascending ( 1 ) or descending ( -1 ) sort order. For single-field indexes, the sort order of keys doesn’t matter because MongoDB can traverse the index in either direction. However, for compound indexes (page 489), sort order can matter in determining whether the index can support a sort operation. 

Consider a collection events that contains documents with the fields username and date . Applications can issue queries that return results sorted first by ascending username values and then by descending (i.e. more recent to last) date values, such as: 

db.events.find().sort( { username: 1, date: -1 } ) 

or queries that return results sorted first by descending username values and then by ascending date values, such as: 

db.events.find().sort( { username: -1, date: 1 } ) 

The following index can support both these sort operations: 

db.events.createIndex( { "username" : 1, "date" : -1 } ) 

However, the above index cannot support sorting by ascending username values and then by ascending date values, such as the following: 

db.events.find().sort( { username: 1, date: 1 } ) 

For more information on sort order and compound indexes, see Use Indexes to Sort Query Results (page 548). 

## Prefixes 

Index prefixes are the beginning subsets of indexed fields. For example, consider the following compound index: 

{ "item": 1, "location": 1, "stock": 1 } 

The index has the following index prefixes: 

• { item: 1 } 

• { item: 1, location: 1 } 

For a compound index, MongoDB can use the index to support queries on the index prefixes. As such, MongoDB can use the index for queries on the following fields: 

• the item field, 

• the item field and the location field, 

• the item field and the location field and the stock field. 

MongoDB can also use the index to support a query on item and stock fields since item field corresponds to a prefix. However, the index would not be as efficient in supporting the query as would be an index on only item and stock . 

However, MongoDB cannot use the index to support queries that include the following fields since without the item field, none of the listed fields correspond to a prefix index: 

• the location field, 

