0
0
MongoDBquery~5 mins

How MongoDB scans documents

Choose your learning style9 modes available
Introduction

MongoDB scans documents to find the data you ask for. It looks through the stored documents to match your query.

When you want to find specific information in a collection.
When you need to filter documents based on certain conditions.
When you want to check how MongoDB searches your data to improve speed.
When you want to understand why a query might be slow.
When you want to learn how MongoDB reads your data behind the scenes.
Syntax
MongoDB
db.collection.find(query)

// MongoDB scans documents in the collection to match the query.
MongoDB scans documents one by one unless there is an index to speed up the search.
If no index matches the query, MongoDB does a full collection scan.
Examples
This finds all user documents where the age is 25. MongoDB scans documents to check the age field.
MongoDB
db.users.find({ age: 25 })
This finds all orders with status 'shipped'. MongoDB scans documents to find matches.
MongoDB
db.orders.find({ status: "shipped" })
This finds products with price greater than 100. MongoDB scans documents to compare prices.
MongoDB
db.products.find({ price: { $gt: 100 } })
Sample Program

This example creates a 'shop' database and adds three products. Then it finds products priced over 10. MongoDB scans each document to check the price.

MongoDB
use shop

// Insert sample documents
 db.products.insertMany([
   { name: "Pen", price: 5 },
   { name: "Notebook", price: 15 },
   { name: "Backpack", price: 50 }
 ])

// Find products with price greater than 10
 db.products.find({ price: { $gt: 10 } })
OutputSuccess
Important Notes

MongoDB uses indexes to avoid scanning every document, which makes queries faster.

Without indexes, MongoDB must scan all documents, which can be slow for large collections.

You can check how MongoDB scans documents using the explain() method.

Summary

MongoDB scans documents to find data matching your query.

Without indexes, it checks every document one by one.

Indexes help MongoDB scan fewer documents and speed up queries.