Database Tutorial #12: MongoDB Indexing and Performance
MongoDB reads every document in a collection if there is no index — a collection scan. At 10 million documents, that is slow. Indexes fix this. Single-Field Index // Create an index on the email field db.users.createIndex({ email: 1 }) // 1 = ascending, -1 = descending // The query now uses the index db.users.find({ email: "alex@example.com" }) // Unique index — enforces uniqueness db.users.createIndex({ email: 1 }, { unique: true }) Compound Index Index multiple fields together when you filter or sort on more than one: ...