Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating and Managing Indexes

Creating and managing indexes in MongoDB

Indexes in MongoDB are used to improve the performance of queries. They allow the database to efficiently locate documents within a collection. Without indexes, MongoDB must scan every document in a collection to select those that match the query.

Creating an Index

To create an index, use the createIndex method. Below is an example of creating an index on the name field:

Create Index Command

db.collection.createIndex({ name: 1 })

Types of Indexes

MongoDB supports several types of indexes, including:

  • Single Field Index: Indexes a single field of a document.
  • Compound Index: Indexes multiple fields of a document.
  • Multikey Index: Indexes the content of an array field.
  • Text Index: Indexes the content of string fields for text search.
  • Geospatial Index: Indexes the content of location data for geospatial queries.

Managing Indexes

Managing indexes involves listing, dropping, and monitoring index usage.

Managing Indexes

// List all indexes
db.collection.getIndexes()

// Drop an index
db.collection.dropIndex("name_1")

// Monitor index usage
db.collection.stats()

Example: Creating a Compound Index

Below is an example of creating a compound index on the firstName and lastName fields:

Compound Index Command

db.collection.createIndex({ firstName: 1, lastName: 1 })