Indexes

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. MongoDB indexes use a B-tree data structure. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

Index for sort

Fundamentally, indexes in MongoDB are similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.

Default _id Index

MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.

Index Types

Single Field Indexes

MongoDB provides complete support for indexes on any field in a collection of documents.

Create an Ascending Index on a Single Field

The following operation creates an ascending index on the score field of the records collection:

db.records.createIndex( { score: 1 } )
{
        "createdCollectionAutomatically" : true,
        "numIndexesBefore" : 0,
        "numIndexesAfter" : 1,
        "ok" : 1
}

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 single-field indexes, the sort order of keys doesn't matter because MongoDB can traverse the index in either direction.

Create an Index on an Embedded Field

You can create indexes on fields within embedded documents, just as you can index top-level fields in documents.

Consider a collection named records that holds documents that resemble the following sample document:

{
    "_id": ObjectId("570c04a4ad233577f97dc459"),
    "score": 1034,
    "location": { "state": "NY", "city": "New York" }
}

The following operation creates an index on the location.state field:

db.records.createIndex( { "location.state": 1 } )

The created index will support queries that select on the field location.state, such as the following:

db.records.find( { "location.state": "CA" } )
db.records.find( { "location.city": "Albany", "location.state": "NY" } )

Create an Index on Embedded Document

You can also create indexes on embedded document as a whole.

The location field is an embedded document, containing the embedded fields city and state. The following command creates an index on the location field as a whole:

db.records.createIndex( { location: 1 } )

Compound Indexes

MongoDB supports compound indexes, where a single index structure holds references to multiple fields within a collection’s documents. MongoDB imposes a limit of 31 fields for any compound index.

Compound indexes can support queries that match on multiple fields.

Create a Compound Index

Consider a collection named products that holds documents that resemble the following document:

{
 "_id": ObjectId(...),
 "item": "Banana",
 "category": ["food", "produce", "grocery"],
 "location": "4th Street Store",
 "stock": 4,
 "type": "cases"
}

The following operation creates an ascending index on the item and stock fields:

db.products.createIndex( { "item": 1, "stock": 1 } )

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. That is, the index supports queries on the item field as well as both item and stock fields:

db.products.find( { item: "Banana" } )
db.products.find( { item: "Banana", stock: { $gt: 5 } } )

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, 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.

db.events.find().sort( { username: 1, date: -1 } )
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 } )

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,
  • the stock field, or
  • the location and stock fields.

Multikey Indexes

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values (e.g. strings, numbers) and nested documents.

Geospatial Index

To support efficient queries of geospatial coordinate data, MongoDB provides two special indexes: 2d indexes that uses planar geometry when returning results and 2dsphere indexes that use spherical geometry to return results.

Text Indexes

MongoDB provides a text index type that supports searching for string content in a collection. These text indexes do not store language-specific stop words (e.g. “the”, “a”, “or”) and stem the words in a collection to only store root words.

Hashed Indexes

To support hash based sharding, MongoDB provides a hashed index type, which indexes the hash of the value of a field. These indexes have a more random distribution of values along their range, but only support equality matches and cannot support range-based queries.

results matching ""

    No results matching ""