0
0
MongoDBquery~5 mins

Query patterns that cause collection scans in MongoDB

Choose your learning style9 modes available
Introduction

Collection scans happen when MongoDB looks through every document in a collection to find matches. This is slow and uses more resources.

When you query a field that has no index.
When you use a query with conditions that MongoDB cannot use indexes for.
When you search with operators that prevent index use, like $not or $regex without a prefix.
When you query on multiple fields but no compound index exists for those fields.
When you use sorting on a field without an index.
Syntax
MongoDB
db.collection.find({ <query> })
If the query cannot use an index, MongoDB performs a collection scan.
Indexes help MongoDB find data faster without scanning all documents.
Examples
If there is no index on the age field, this query causes a collection scan.
MongoDB
db.users.find({ age: 25 })
Using $not can prevent index use, causing a collection scan.
MongoDB
db.orders.find({ status: { $not: { $eq: "shipped" } } })
A regex without a fixed prefix causes a collection scan.
MongoDB
db.products.find({ name: /phone/ })
If no compound index exists on region and product, this query may cause a collection scan.
MongoDB
db.sales.find({ region: "west", product: "book" })
Sample Program

This query searches for items in the 'toys' category. Without an index on 'category', MongoDB scans the whole collection.

MongoDB
use shop
// Assume no index on 'category'
db.items.find({ category: "toys" })
OutputSuccess
Important Notes

Creating indexes on frequently queried fields helps avoid collection scans.

Use explain() to check if a query uses an index or does a collection scan.

Collection scans are okay for small collections but slow down large ones.

Summary

Collection scans happen when no suitable index exists for a query.

Queries using fields without indexes or certain operators cause collection scans.

Indexes improve query speed by avoiding collection scans.