MongoDB Documentation, Release 3.0.4 Create an Index to Support Read Operations If your application queries a collection on a particular field or set of fields, then an index on the queried field or a compound index (page 489) on the set of fields can prevent the query from scanning the whole collection to find and return the query results. For more information about indexes, see the complete documentation of indexes in MongoDB (page 486). An application queries the inventory collection on the type field. The value of the type field is user-driven. var typeValue = <someUserInput>; db.inventory.find( { type: typeValue } ); To improve the performance of this query, add an ascending or a descending index to the inventory collection on the type field. 2 In the mongo shell, you can create indexes using the db.collection.createIndex() method: db.inventory.createIndex( { type: 1 } ) This index can prevent the above query on type from scanning the whole collection to return the results. To analyze the performance of the query with an index, see Analyze Query Performance (page 111). In addition to optimizing read operations, indexes can support sort operations and allow for a more efficient storage utilization. See db.collection.createIndex() and Indexing Tutorials (page 517) for more information about index creation. Query selectivity refers to how well the query predicate excludes or filters out documents in a collection. Query selectivity can determine whether or not queries can use indexes effectively or even use indexes at all. More selective queries match a smaller percentage of documents. For instance, an equality match on the unique _id field is highly selective as it can match at most one document. Less selective queries match a larger percentage of documents. Less selective queries cannot use indexes effectively or even at all. For instance, the inequality operators $nin and $ne are not very selective since they often match a large portion of the index. As a result, in many cases, a $nin or $ne query with an index may perform no better than a $nin or $ne query that must scan all documents in a collection. The selectivity of regular expressions depends on the expressions themselves. For details, see regular expres- sion and index use . An index covers (page 66) a query when both of the following apply: For example, a collection inventory has the following index on the type and item fields: • all the fields in the query (page 96) are part of an index, and • all the fields returned in the results are in the same index. Query Selectivity Covered Query Example 2 For single-field indexes, the selection between ascending and descending order is immaterial. For compound indexes, the selection is important. See indexing order (page 490) for more details. Chapter 3. MongoDB CRUD Operations 66