Single Field Index in MongoDB: Definition and Usage
single field index in MongoDB is an index created on one specific field of a document to speed up queries filtering or sorting by that field. It helps MongoDB quickly locate data without scanning the entire collection.How It Works
Imagine a phone book where names are listed alphabetically. Instead of flipping through every page to find a name, you can quickly jump to the right section because the book is organized. A single field index in MongoDB works similarly by organizing data based on one field, like a name or date.
When you create a single field index on a field, MongoDB builds a special data structure that keeps track of the values in that field and where to find them in the collection. This means when you search or sort by that field, MongoDB uses the index to jump directly to the matching documents instead of checking every document one by one.
Example
This example shows how to create a single field index on the username field in a MongoDB collection called users. Then it demonstrates a query that benefits from this index.
db.users.createIndex({ username: 1 })
db.users.find({ username: "alice" })When to Use
Use a single field index when you often search, filter, or sort your data by one specific field. For example, if your app frequently looks up users by their email or username, creating a single field index on that field speeds up those queries.
This is especially helpful in large collections where scanning every document would be slow. However, avoid creating too many indexes as they take extra space and slow down writes.
Key Points
- A single field index is built on one field of documents.
- It improves query speed for searches and sorts on that field.
- Indexes use extra storage and can slow down data writes.
- Use them when queries frequently filter or sort by a single field.