A single field index helps the database find data faster when searching by one specific field.
Single field index in MongoDB
db.collection.createIndex({ fieldName: 1 })The 1 means the index is in ascending order.
You can also use -1 for descending order, but it usually works the same for single fields.
email field in the users collection.db.users.createIndex({ email: 1 })price field in the products collection.db.products.createIndex({ price: -1 })orderDate field in the orders collection.db.orders.createIndex({ orderDate: 1 })This example switches to the shopDB database, creates an ascending index on the category field in the products collection, then finds all products where the category is 'books'. The index helps this search run faster.
use shopDB // Create a single field index on the 'category' field db.products.createIndex({ category: 1 }) // Find all products in the 'books' category const results = db.products.find({ category: 'books' }).toArray() results
Creating an index takes some time and uses extra space, so only create indexes you really need.
Indexes speed up searches but slow down writes (inserts, updates) a bit because the index must be updated.
You can check existing indexes with db.collection.getIndexes().
Single field indexes speed up queries on one field.
Create them with createIndex({ field: 1 }).
Use them when you search or sort often by that field.