Indexes
An index lets MongoDB find matching documents without scanning the whole collection — the same tradeoff SQL indexes make: faster reads, in exchange for extra work on every write.
Creating an index
JS mongosh
db.posts.createIndex({ author: 1 })
Output
author_1
The 1 means ascending order (-1 would be descending). MongoDB returns the generated index name. Now a query filtering on author can jump straight to matching documents instead of checking every document in the collection one by one.
Seeing what indexes exist
JS mongosh
db.posts.getIndexes()
Output
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { author: 1 }, name: 'author_1' }
]Every collection automatically gets an index on _id — that one you never have to create yourself.
Unique indexes
JS mongosh
db.users.createIndex({ email: 1 }, { unique: true })
Output
email_1
A unique index rejects any insert or update that would create a duplicate value in that field — the same role a UNIQUE constraint plays on a SQL column.
Note: an index makes reads on that field fast, but it isn't free — every insert, update, or delete has to update every index on the collection too, and each index takes up disk space. Indexing every field "just in case" slows down writes for a benefit you may never use. Add indexes for the queries your application actually runs, not preemptively for every field.