What are indexes in MongoDB?

Answer

Indexes in MongoDB improve query performance by allowing the database to find documents without a full collection scan. Without an index, MongoDB must scan every document (COLLSCAN). With an index, it can quickly jump to matching documents (IXSCAN). Default index: every collection has an index on _id automatically. Creating indexes: db.users.createIndex({ email: 1 }) — single field index, ascending (1); db.users.createIndex({ email: -1 }) — descending; db.users.createIndex({ lastName: 1, firstName: 1 }) — compound index (multiple fields). Index types: Single field: on one field; Compound: multiple fields — order matters (leftmost prefix rule); Multikey: automatically created when indexing array fields — one index entry per array element; Text: for full-text search; 2dsphere: for GeoJSON geospatial; Hashed: for hash-based sharding; Wildcard: indexes all fields or a subset dynamically. Index options: unique: true — enforces uniqueness; sparse: true — only indexes documents that contain the field; expireAfterSeconds — TTL index; background: true (legacy) — build without blocking. View indexes: db.users.getIndexes(). Drop index: db.users.dropIndex("email_1"). Indexes trade write performance for read performance — don't over-index.