Index Arrays with Embedded Documents You can create multikey indexes on array fields that contain nested objects. 

Consider an inventory collection with documents of the following form: 

{ _id: 1, item: "abc", stock: [ { size: "S", color: "red", quantity: 25 }, { size: "S", color: "blue", quantity: 10 }, { size: "M", color: "blue", quantity: 50 } ] } { _id: 2, item: "def", stock: [ { size: "S", color: "blue", quantity: 20 }, { size: "M", color: "blue", quantity: 5 }, { size: "M", color: "black", quantity: 10 }, { size: "L", color: "red", quantity: 2 } ] } { _id: 3, item: "ijk", stock: [ { size: "M", color: "blue", quantity: 15 }, { size: "L", color: "blue", quantity: 100 }, { size: "L", color: "red", quantity: 25 } ] } ... 

The following operation creates a multikey index on the stock.size and stock.quantity fields: 

db.inventory.createIndex( { "stock.size": 1, "stock.quantity": 1 } ) 

The compound multikey index can support queries with predicates that include both indexed fields as well as predicates that include only the index prefix "stock.size" , as in the following examples: 

db.inventory.find( { "stock.size": "M" } ) db.inventory.find( { "stock.size": "S", "stock.quantity": { $gt: 20 } } ) 

For details on how MongoDB can combine multikey index bounds, see Multikey Index Bounds (page 511). For more information on behavior of compound indexes and prefixes, see compound indexes and prefixes (page 490). 

The compound multikey index can also support sort operations, such as the following examples: 

db.inventory.find( ).sort( { "stock.size": 1, "stock.quantity": 1 } ) db.inventory.find( { "stock.size": "M" } ).sort( { "stock.quantity": 1 } ) 

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

