SlideShare a Scribd company logo
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

MongoDB_ppt.pptx
MongoDB_ppt.pptxMongoDB_ppt.pptx
MongoDB_ppt.pptx
1AP18CS037ShirishKul
 
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 Scale
MongoDB
 
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
AshishRathore72
 
unit 4,Indexes in database.docx
unit 4,Indexes in database.docxunit 4,Indexes in database.docx
unit 4,Indexes in database.docx
RaviRajput416403
 
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
mh3473
 
Mongo db
Mongo dbMongo db
Mongo db
Gyanendra Yadav
 
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
 
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
TO 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 -MyWhitePaper
Rajesh Kumar
 
Mongodb
MongodbMongodb
Mongodb
Thiago Veiga
 
MongoDB - An Introduction
MongoDB - An IntroductionMongoDB - An Introduction
MongoDB - An Introduction
dinkar thakur
 
Novedades de MongoDB 3.6
Novedades de MongoDB 3.6Novedades de MongoDB 3.6
Novedades de MongoDB 3.6
MongoDB
 
Elasticsearch an overview
Elasticsearch   an overviewElasticsearch   an overview
Elasticsearch an overview
Amit 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 MySQL
Márton Kodok
 
MongoDB
MongoDBMongoDB
MongoDB
wiTTyMinds1
 
Introduction to mongo db
Introduction to mongo dbIntroduction to mongo db
Introduction to mongo db
Lawrence 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.2
MongoDB
 

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

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 

Recently uploaded (20)

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 

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/