SlideShare a Scribd company logo
1 of 20
Indexing and Query Performance
in MongoDB
Malak Abu Hammad
Introduction
● The Dual Challenge: Ensuring data retrieval is swift while managing resources
effectively.
● Role of Indexing: The bridge to effective and efficient querying.
So .. What’s an Index?
● Indexes are data structures that support the efficient execution of queries in
MongoDB. They contain copies of parts of the data in documents to make queries
more efficient.
● Without indexes, MongoDB must scan every document in a collection to find the
documents that match each query.
● Types of indexes:
○ Single index
○ Compound index
Query Structure
● Query criteria
● Options, such as read concern
● Projection criteria (optional)
db.collection.find(
{name: “malak”},
{birthdate : 1, _id : 0}
).readConcern("majority")
Why Indexing is Essential?
● Read Performance: Faster data access, reduced wait times.
● Resource Management: Efficient CPU and memory utilization.
Creating and Managing Indexes
● Create single index
db.collection.createIndex(
{field: 1},
{
unique: true,
name: “abc”
}
)
● Viewing Indexes
db.collection.getIndexes();
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"status" : 1
},
"name" : "status_1"
}
]
Compound Indexes
● Create compound index index
db.collection.createIndex(
{
field1: 1,
field2: -1
},
{
unique: true,
name: “abc”
}
)
● Order of fields in index and in a
query matters.
● Prefixes
For instance, if you have a compound index on
{a: 1, b: 1, c: 1}
The possible prefix indexes are
● {a: 1}
● {a: 1, b: 1}
MongoDB can use the compound index for queries
that filter on:
● Only a
● Both a and b
● All a, b, and c
Special Index Types and Use Cases
● Text Indexes: For searching text content in documents.
● Geospatial Indexes: Finding items within proximity.
● Wildcard Indexes: Flexible indexing for evolving schemas.
Performance Analysis
● Explain Method: Understanding how MongoDB executes a query.
● Spotting Slow Queries: Using MongoDB logs and monitoring tools.
○ MongoDB has a built-in profiler that logs all operations taking longer than a specified threshold.
Visual tools can represent this data, making it easy to spot problematic operations or patterns.
● Visualization
○ Visual tools can represent this data, making it easy to spot problematic operations or patterns.
○ Such as: Atlas , Compass
Performance Analysis - Explain Method
db.collection.find({quantity: {$gte: 100, $lte: 200}})
.explain("executionStats")
{// without index
queryPlanner: {
...
winningPlan: {
queryPlan: {
stage: 'COLLSCAN',
}
}
},
executionStats: {
executionSuccess: true,
nReturned: 3,
executionTimeMillis: 0,
totalKeysExamined: 0,
totalDocsExamined: 10,
executionStages: {
stage: 'COLLSCAN',
},
},
}
{ //with index
queryPlanner: {
winningPlan: {
queryPlan: {
stage: 'FETCH',
inputStage: {
stage: 'IXSCAN',
keyPattern: {
quantity: 1
},
}
}
},
rejectedPlans: [ ]
},
executionStats: {
executionSuccess: true,
nReturned: 3,
executionTimeMillis: 0,
totalKeysExamined: 3,
totalDocsExamined: 3,
executionStages: {
},
},
}
Query Optimization
● Index Selection
○ Query Planner
MongoDB's query planner evaluates the available indexes and chooses the most efficient way to
execute the query. The following steps are taken:
■ Candidate Indexes
■ Plan Generation
■ Plan Evaluation
○ Index Intersection
○ Query Selectivity
○ Cache
○ Impact of Write Operations
● Hint Method: Forcing a specific index.
● Covered Queries: Efficiently fetching data without scanning documents.
Covered query
A covered query is a query that can be satisfied entirely using an index and
does not have to examine any documents
An index covers a query if this criteria applies:
● All the fields in the query are part of an index, and
● All the fields returned in the results are in the same index, and
● No fields in the query are equal to null (i.e. {"field" : null} or {"field" : {$eq :
null}} ).
Write Performance & Indexes
● The Trade-off: Every index adds to write overhead.
● Striking a Balance: Periodic assessment is mandatory.
Index Maintenance
● Fragmentation: Over time, index
efficiency can degrade.
● Rebuilding: Periodically refreshing
indexes.
db.collection.reIndex()
● Monitoring: Using built-in tools to
watch index performance.
Best Practices
● Avoid Over-indexing: Too many indexes can backfire.
● Analyze Workloads: Adjust indexing strategies based on real-world usage.
● Operational Overhead: Be aware of the cost of maintaining indexes.
Case Study: E-Commerce Platform Product Search Optimization
An e-commerce platform, named "ShopMMS" was experiencing performance issues. As
they scaled and added more products, users began to report slow search times when
looking for products. The platform was built on a MongoDB backend.
Problem
● As the number of products grew into the millions, searches that used to take
milliseconds started taking several seconds.
● The platform's reviews and ratings system, which allowed users to filter and sort
products based on ratings, added further complexity to the search queries.
Questions & Answers
Further Resources
● Official MongoDB Documentation
https://www.mongodb.com/docs/manual/indexes/
● MongoDB University: M201: MongoDB Performance
https://learn.mongodb.com/courses/m201-mongodb-performance
● “Indexing and Query Performance in MongoDB” presentation will be available on
slideshare
https://www.slideshare.net/mms414/
Feedback & Networking
● MongoDB Arabic Community
Linkedin: https://www.linkedin.com/company/mongodb-arabic-community/
ً‫ا‬‫ﺷﻜﺮ‬
Thank you

More Related Content

Similar to Indexing and Query Performance in MongoDB.pdf

Fast querying indexing for performance (4)
Fast querying   indexing for performance (4)Fast querying   indexing for performance (4)
Fast querying indexing for performance (4)MongoDB
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleMongoDB
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesAshishRathore72
 
unit 4,Indexes in database.docx
unit 4,Indexes in database.docxunit 4,Indexes in database.docx
unit 4,Indexes in database.docxRaviRajput416403
 
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxMOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxmh3473
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlTO THE NEW | Technology
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaperRajesh Kumar
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introductiondinkar thakur
 
Novedades de MongoDB 3.6
Novedades de MongoDB 3.6Novedades de MongoDB 3.6
Novedades de MongoDB 3.6MongoDB
 
Elasticsearch an overview
Elasticsearch   an overviewElasticsearch   an overview
Elasticsearch an overviewAmit Juneja
 
Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011bostonrb
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo dbLawrence Mwai
 
MongoDB 3.2 - a giant leap. What’s new?
MongoDB 3.2 - a giant leap. What’s new?MongoDB 3.2 - a giant leap. What’s new?
MongoDB 3.2 - a giant leap. What’s new?Binary Studio
 
Webinar : Nouveautés de MongoDB 3.2
Webinar : Nouveautés de MongoDB 3.2Webinar : Nouveautés de MongoDB 3.2
Webinar : Nouveautés de MongoDB 3.2MongoDB
 

Similar to Indexing and Query Performance in MongoDB.pdf (20)

MongoDB_ppt.pptx
MongoDB_ppt.pptxMongoDB_ppt.pptx
MongoDB_ppt.pptx
 
Fast querying indexing for performance (4)
Fast querying   indexing for performance (4)Fast querying   indexing for performance (4)
Fast querying indexing for performance (4)
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You Scale
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practices
 
unit 4,Indexes in database.docx
unit 4,Indexes in database.docxunit 4,Indexes in database.docx
unit 4,Indexes in database.docx
 
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptxMOOC_PRESENTATION_FINAL_PART_1[1].pptx
MOOC_PRESENTATION_FINAL_PART_1[1].pptx
 
Mongo db
Mongo dbMongo db
Mongo db
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
 
MongoDB NoSQL database a deep dive -MyWhitePaper
MongoDB  NoSQL database a deep dive -MyWhitePaperMongoDB  NoSQL database a deep dive -MyWhitePaper
MongoDB NoSQL database a deep dive -MyWhitePaper
 
Mongodb
MongodbMongodb
Mongodb
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
 
Novedades de MongoDB 3.6
Novedades de MongoDB 3.6Novedades de MongoDB 3.6
Novedades de MongoDB 3.6
 
Elasticsearch an overview
Elasticsearch   an overviewElasticsearch   an overview
Elasticsearch an overview
 
Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011Mongodb in-anger-boston-rb-2011
Mongodb in-anger-boston-rb-2011
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
 
MongoDB
MongoDBMongoDB
MongoDB
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
 
MongoDB 3.2 - a giant leap. What’s new?
MongoDB 3.2 - a giant leap. What’s new?MongoDB 3.2 - a giant leap. What’s new?
MongoDB 3.2 - a giant leap. What’s new?
 
Webinar : Nouveautés de MongoDB 3.2
Webinar : Nouveautés de MongoDB 3.2Webinar : Nouveautés de MongoDB 3.2
Webinar : Nouveautés de MongoDB 3.2
 

Recently uploaded

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Recently uploaded (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Indexing and Query Performance in MongoDB.pdf

  • 1. Indexing and Query Performance in MongoDB Malak Abu Hammad
  • 2. Introduction ● The Dual Challenge: Ensuring data retrieval is swift while managing resources effectively. ● Role of Indexing: The bridge to effective and efficient querying.
  • 3. So .. What’s an Index? ● Indexes are data structures that support the efficient execution of queries in MongoDB. They contain copies of parts of the data in documents to make queries more efficient. ● Without indexes, MongoDB must scan every document in a collection to find the documents that match each query. ● Types of indexes: ○ Single index ○ Compound index
  • 4. Query Structure ● Query criteria ● Options, such as read concern ● Projection criteria (optional) db.collection.find( {name: “malak”}, {birthdate : 1, _id : 0} ).readConcern("majority")
  • 5. Why Indexing is Essential? ● Read Performance: Faster data access, reduced wait times. ● Resource Management: Efficient CPU and memory utilization.
  • 6. Creating and Managing Indexes ● Create single index db.collection.createIndex( {field: 1}, { unique: true, name: “abc” } ) ● Viewing Indexes db.collection.getIndexes(); [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "status" : 1 }, "name" : "status_1" } ]
  • 7. Compound Indexes ● Create compound index index db.collection.createIndex( { field1: 1, field2: -1 }, { unique: true, name: “abc” } ) ● Order of fields in index and in a query matters. ● Prefixes For instance, if you have a compound index on {a: 1, b: 1, c: 1} The possible prefix indexes are ● {a: 1} ● {a: 1, b: 1} MongoDB can use the compound index for queries that filter on: ● Only a ● Both a and b ● All a, b, and c
  • 8. Special Index Types and Use Cases ● Text Indexes: For searching text content in documents. ● Geospatial Indexes: Finding items within proximity. ● Wildcard Indexes: Flexible indexing for evolving schemas.
  • 9. Performance Analysis ● Explain Method: Understanding how MongoDB executes a query. ● Spotting Slow Queries: Using MongoDB logs and monitoring tools. ○ MongoDB has a built-in profiler that logs all operations taking longer than a specified threshold. Visual tools can represent this data, making it easy to spot problematic operations or patterns. ● Visualization ○ Visual tools can represent this data, making it easy to spot problematic operations or patterns. ○ Such as: Atlas , Compass
  • 10. Performance Analysis - Explain Method db.collection.find({quantity: {$gte: 100, $lte: 200}}) .explain("executionStats") {// without index queryPlanner: { ... winningPlan: { queryPlan: { stage: 'COLLSCAN', } } }, executionStats: { executionSuccess: true, nReturned: 3, executionTimeMillis: 0, totalKeysExamined: 0, totalDocsExamined: 10, executionStages: { stage: 'COLLSCAN', }, }, } { //with index queryPlanner: { winningPlan: { queryPlan: { stage: 'FETCH', inputStage: { stage: 'IXSCAN', keyPattern: { quantity: 1 }, } } }, rejectedPlans: [ ] }, executionStats: { executionSuccess: true, nReturned: 3, executionTimeMillis: 0, totalKeysExamined: 3, totalDocsExamined: 3, executionStages: { }, }, }
  • 11. Query Optimization ● Index Selection ○ Query Planner MongoDB's query planner evaluates the available indexes and chooses the most efficient way to execute the query. The following steps are taken: ■ Candidate Indexes ■ Plan Generation ■ Plan Evaluation ○ Index Intersection ○ Query Selectivity ○ Cache ○ Impact of Write Operations ● Hint Method: Forcing a specific index. ● Covered Queries: Efficiently fetching data without scanning documents.
  • 12. Covered query A covered query is a query that can be satisfied entirely using an index and does not have to examine any documents An index covers a query if this criteria applies: ● All the fields in the query are part of an index, and ● All the fields returned in the results are in the same index, and ● No fields in the query are equal to null (i.e. {"field" : null} or {"field" : {$eq : null}} ).
  • 13. Write Performance & Indexes ● The Trade-off: Every index adds to write overhead. ● Striking a Balance: Periodic assessment is mandatory.
  • 14. Index Maintenance ● Fragmentation: Over time, index efficiency can degrade. ● Rebuilding: Periodically refreshing indexes. db.collection.reIndex() ● Monitoring: Using built-in tools to watch index performance.
  • 15. Best Practices ● Avoid Over-indexing: Too many indexes can backfire. ● Analyze Workloads: Adjust indexing strategies based on real-world usage. ● Operational Overhead: Be aware of the cost of maintaining indexes.
  • 16. Case Study: E-Commerce Platform Product Search Optimization An e-commerce platform, named "ShopMMS" was experiencing performance issues. As they scaled and added more products, users began to report slow search times when looking for products. The platform was built on a MongoDB backend. Problem ● As the number of products grew into the millions, searches that used to take milliseconds started taking several seconds. ● The platform's reviews and ratings system, which allowed users to filter and sort products based on ratings, added further complexity to the search queries.
  • 18. Further Resources ● Official MongoDB Documentation https://www.mongodb.com/docs/manual/indexes/ ● MongoDB University: M201: MongoDB Performance https://learn.mongodb.com/courses/m201-mongodb-performance ● “Indexing and Query Performance in MongoDB” presentation will be available on slideshare https://www.slideshare.net/mms414/
  • 19. Feedback & Networking ● MongoDB Arabic Community Linkedin: https://www.linkedin.com/company/mongodb-arabic-community/