Concept Flow - Query patterns that cause collection scans
Receive Query
Check for Indexes
Use Index
Return Results
End
The database receives a query, checks if an index can be used, and if not, performs a collection scan to find matching documents.
db.users.find({ age: { $gt: 30 } })| Step | Action | Index Available? | Operation | Documents Examined | Result |
|---|---|---|---|---|---|
| 1 | Receive query { age: { $gt: 30 } } | Unknown | Check indexes | 0 | Proceed |
| 2 | Check if index on 'age' exists | No | Decide operation | 0 | No index found |
| 3 | Perform collection scan | No | Scan all documents | 1000 | Filter documents with age > 30 |
| 4 | Return matching documents | No | Return results | N/A | Documents with age > 30 |
| 5 | End query execution | No | Complete | N/A | Query finished |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| indexExists | Unknown | False | False | False |
| documentsExamined | 0 | 0 | 1000 | 1000 |
| matchingDocuments | 0 | 0 | Variable | Variable |
Query patterns without matching indexes cause collection scans. Database checks for indexes first. If no index, scans all documents. Collection scans are slower on large data. Create indexes on queried fields to avoid scans.
age?{ age: { $gt: 25 } } uses range operator on indexed field, avoiding collection scan. Queries with $where or $regex often cause scans.products with an index on category, what will be the result of this query?db.products.find({ category: { $in: ['electronics', 'books'] } })category is indexed, MongoDB uses the index to find documents where category is 'electronics' or 'books'.orders with an index on status. Which query will cause a collection scan and how can you fix it?db.orders.find({ $where: 'this.status === "shipped"' }){ status: 'shipped' } uses the index on status, avoiding collection scan.users collection:db.users.find({ $or: [ { age: { $gt: 30 } }, { name: /John/ } ] })age and name, which change will prevent collection scans?age and one on name--each using indexes, then combining results in application avoids scans.Pass the test and this pattern moves unknown