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

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

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/