Indexes in MongoDB improve the performance of search operations by providing efficient ways to find data. Without indexes, MongoDB would need to scan every document in a collection to fulfill a query, which can be slow, especially with large datasets.
- Speed: They speed up query performance by reducing the amount of data MongoDB needs to scan.
- Efficiency: They help optimize query operations such as find(), update(), and delete().
- Sorting: They enable efficient sorting of documents when used with the $sort stage in aggregation.
- Single Field Index: Indexes a single field of a document.
- Compound Index: Indexes multiple fields of a document, useful when queries need to filter or sort based on multiple fields.
- Multikey Index: Used when the indexed field is an array.
- Text Index: Enables full-text search on string fields.
db.collection.createIndex({ "email": 1 }) // 1 for ascending order
db.collection.createIndex({ "name": 1, "age": -1 }) // 1 for ascending, -1 for descending
db.products.createIndex({ "description": "text" })
A transaction in MongoDB allows you to execute multiple operations across multiple documents and collections in a way that ensures atomicity — either all operations in the transaction succeed, or none of them do. This is crucial for maintaining data consistency in applications where multiple operations need to be performed together.
- Multiple Operations: When multiple operations need to be treated as a single unit of work.
- Cross-Collection Operations: When working with multiple collections within a single operation.
- Atomicity: When you need to ensure that changes are rolled back if something fails.
- Atomicity: All operations within a transaction are treated as a single unit. If one operation fails, the transaction is rolled back.
-
Consistency: Ensures that the database state is consistent before and after the transaction.
-
Isolation: Ensures that operations in a transaction are isolated from other transactions.
-
Durability: Ensures that once a transaction is committed, it will persist, even in the case of system failures.