0
0
MongoDBquery~5 mins

Single field index in MongoDB

Choose your learning style9 modes available
Introduction

A single field index helps the database find data faster when searching by one specific field.

When you often search for documents by one field, like finding users by their email.
When you want to speed up queries that filter or sort by a single field.
When you want to improve performance on lookups using a specific field.
When you want to enforce uniqueness on a single field (using the { unique: true } option), like usernames.
When you want to reduce the time it takes to find records in large collections.
Syntax
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.

Examples
This creates an ascending index on the email field in the users collection.
MongoDB
db.users.createIndex({ email: 1 })
This creates a descending index on the price field in the products collection.
MongoDB
db.products.createIndex({ price: -1 })
This creates an ascending index on the orderDate field in the orders collection.
MongoDB
db.orders.createIndex({ orderDate: 1 })
Sample Program

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.

MongoDB
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
OutputSuccess
Important Notes

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().

Summary

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.