Index Scan vs Collection Scan in MongoDB: Key Differences and Usage
collection scan reads every document in a collection to find matches, which is slower for large data sets. An index scan uses an index to quickly locate matching documents, making queries faster and more efficient.Quick Comparison
This table summarizes the main differences between index scan and collection scan in MongoDB.
| Factor | Index Scan | Collection Scan |
|---|---|---|
| Speed | Fast for large collections | Slow, scans all documents |
| Resource Usage | Uses index data structures | Reads entire collection data |
| Use Case | When suitable index exists | When no index matches query |
| Query Efficiency | Efficient for selective queries | Inefficient for large data |
| Result Accuracy | Returns matching documents only | Returns matching documents after full scan |
| Explain Output | Shows index usage in query plan | Shows COLLSCAN in query plan |
Key Differences
An index scan in MongoDB uses a pre-built index to quickly find documents that match the query criteria. This means MongoDB does not have to look at every document in the collection, which saves time and computing resources. Indexes are like a book's index, pointing directly to the pages (documents) you need.
On the other hand, a collection scan means MongoDB reads every document in the collection to check if it matches the query. This is like reading every page in a book to find a word. It is slower and uses more resources, especially if the collection is large.
When you run db.collection.find(query).explain(), an index scan will show the index used in the query plan, while a collection scan will show COLLSCAN. Index scans improve performance but require indexes to be created and maintained, while collection scans work without indexes but are less efficient.
Code Comparison
db.users.createIndex({ age: 1 })
db.users.find({ age: { $gt: 30 } }).explain('executionStats')Collection Scan Equivalent
db.users.dropIndex('age_1') db.users.find({ age: { $gt: 30 } }).explain('executionStats')
When to Use Which
Choose index scan when your queries filter on fields that have indexes, especially for large collections. This makes queries faster and reduces server load. Always create indexes on fields you query often.
Use collection scan only when no suitable index exists or for small collections where scanning all documents is not costly. Avoid collection scans on large collections as they slow down performance.