This chapter introduces MongoDB indexes. Similar to MYSQL, MongoDB also supports indexes. The difference is that MongoDB supports adding indexes to any nested field of the JSON structure, with the same purpose of improving query efficiency.

Types of MongoDB Indexes

Single Field Index

Similar to MYSQL, creating an index for a single field

Format:

db.collection.createIndex( { field_name: sorting_direction(1 or -1) } )

Note: Sorting direction 1 represents ascending order, and -1 represents descending order.

Example 1:

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

Creates an index for the score field.

Example 2:

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

Creates an index for the nested JSON field location.state.

Compound Index

Similar to MYSQL, multiple fields can be combined to create an index, accelerating the speed of compound queries.

Format:

db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )

Example:

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

Creates a compound index for the item and stock fields, both in ascending order (1 represents ascending order).

Text Index (Full-text Index)

Text index (text) is mainly used to support full-text search.

Note: A collection only allows one text index, but a text index can include multiple fields.

Example:

db.stores.createIndex( { name: "text", description: "text" } )

Creates a text full-text index for the name and description fields.

Note: For details, please refer to the Full Text Index section.

Spatial Index (GEO Index)

Primarily used to support geographical information-related queries, mainly supporting two types of index: 2dsphere and 2d. For details, please refer to the Geospatial Query section.

Deleting Indexes

To list all the indexes in a collection:

db.pets.getIndexes()

To delete the catIdx index from the pets collection:

db.pets.dropIndex( "catIdx" )