SlideShare a Scribd company logo
Introduction to MongoDB
Execution Plan & Optimizer
Interested in Open Source technologies
Active MongoDB Community Contributor
Tech Speaker/Blogger
Senior DevOps and MongoDB Consultant
Manosh Malai
About Me
Consulting
Services
Managed
Services
Focuses on MySQL and MongoDB
Mydbops Services
250 + Clients In 3 Yrs. of Operations
Our Clients
MongoDB Execution Plan Analysis
MongoDB Optimizer and Plan Cache
Query in the MongoDB Execution Layer
Agenda
Query In The MongoDB Execution Layer
Client net listener
thread_conn
Query Decode
Operation
Context
Catalog
MapLayer
Canonical Plan
Plan Executor Optimizer
RecordStore & Cursor Snapshot
A client connects to MongoDB and creates a new thread to handle all requests.
Some Query(Such as insert) does not need to execute the plan, It will directly interact with the engine
through RecordStore.
Query performs simple processing (standardization) and builds some context data structures into
CanonicalQuery.
The Plan module is qualified for generating multiple execution plans for the Query, then delivering it to
the Optimizer to select the best one and surrendering it to the PlanExecutor.
PlanExecutor step by step according to the execution plan to obtain the final data (or perform the
update to modify the data).
Query Statement Execution Algorithm
Current version of Explain has three mode:
queryPlanner
executionStats
allPlansExecution
db.collection.find().explain()
Execution Plan Analysis
MongoDB Execution Plan Analysis
queryPlanner is the default mode of the current version of explain.
The queryPlanner mode does not actually query the query statement.
Performs an execution plan analysis for the query statement and selects the winning plan.
queryPlanner.winningPlan.stage: COLLSCAN
Without Index
queryPlanner.winningPlan.stage: FETCH
With Index
queryPlanner Mode
queryPlanner + executionStats information of the evaluated query.
With Index
explain.queryPlanner.indexFilterSet
explain.queryPlanner.winningPlan.stage
explain.executionStats.nReturned
explain.executionStats.executionTimeMillis
explain.executionStats.totalKeysExamined
explain.executionStats.totalDocsExamined
explain.executionStats.executionStages.advanced
explain.executionStats.executionStages.works
explain.executionStats.executionStages.inputStage.docsExamined
explain.executionStats.executionStages.isEOF
executionStats Mode
EX
db.runCommand( {
planCacheSetFilter: "orders",
query: { status: "A" },
indexes: [ { cust_id: 1, status: 1 },
{ status: 1, order_date: -1 } ]
} )
IndexFilter determines how the query
optimizer will use index for a type of
query.
Thquery optimizer will ignore the index
set by the
1. explain.queryPlanner.indexFilterSet
The stage of the optimal execution plan
2. explain.queryPlanner.winningPlan.stage
COLLSCAN: Full table scan
IXSCAN: Index scan
FETCH: Retrieve the specified document based on the indexEmpty text
SHARD_MERGE: Return each fragment to the data for merge
SORT: Indicates that sorting is done in memor
LIMIT: Use limit to limit the number of returns
SKIP: Skip using skip
IDHACK: Query for _id
SHARDING_FILTER: Querying fragmented data by mongos
COUNT: Count operation using db.coll.explain().count()
COUNTSCAN: Count does not use the stage return when using Count for
index
COUNT_SCAN: Count uses the stage to return when the index is counted
SUBPLA: Stage return of $or query not used to index
TEXT: Stage return when using full-text index for queryPROJECTION: The
return of the stage when the return field is qualified
STAGE
executionStats Metrics
executionStats Metrics
The number of returns returned by the query 
3. explain.executionStats.nReturned
Overall execution time
4. explain.executionStats.executionTimeMillis
Number of index scans
5. explain.executionStats.totalKeysExamined
Document scans
6. explain.executionStats.totalDocsExamined
executionStats.inputStage Metrics
8. explain.executionStats.executionStages.works
7. explain.executionStats.executionStages.advanced
9. explain.executionStats.executionStage.isEOF
The planner ask plan each time for the next document via call to work()
If the plan can give supply document it respond with document, Otherwise the plan respond with
needTime
If all the all the document have been retrieved then isEOF = 1
Work - Advanced - isEOF [ Algorithm ]
"works": 18667
"advanced": 18666
"needTime": 0
WorkingSet workingSet;
PlanStage* rootStage = makeQueryPlan(&workingSet, ...);
while (!rootStage->isEOF()) {
WorkingSetID result;
switch(rootStage->work(&result)) {
case PlanStage::ADVANCED:
// do something with result
WorkingSetMember* member = workingSet.get(result);
cout << "Result: " << member->obj << std::endl;
break;
case PlanStage::IS_EOF:
// All done. Will fall out of while loop.
break;
Work - Advanced - isEOF [ Code ]
Cont . .
case PlanStage::NEED_TIME:
// Need more time.
break;
case PlanStage::FAILURE:
// Throw exception or return error.
break;
}
if (shouldYield) {
// Occasionally yield.
stage->saveState();
stage->restoreState();
}
}
As the name suggests, the allPlanExxecution mode is to perform all
execution plans in the executionStats mode. It will show all candidate
Rejected Plans.
allPlansExecution Mode
Plan Optimizer and Plan Cache
Find Matching
Cache Entry
Empty
text
Evaluate Plan
Performance
Generate
Candidate Plans
Query
Empty
text
Evaluate
Candidate Plans
Choose Winning
Plans
Create Cache
Entry
Generate Result
Documents
Evict Cache
Entry
NO MATCH
MATCH
FAIL
PASS
Plan Optimiser
QueryPlanner Canonical Query
Canonical Query * No of Indexes based on
predicate Conditions = Candidate Plane
Select a Wining Plane and Add it Plane Cache
Ranking the Candidate Plane
db.setLogLevel(2,'query')
db.people.getPlanCache().clear()
db.people.find({"birthday": { $gte: new ISODate("2016-03-22T11:34:15Z")}},
{first_name:1, birthday:1, employer:1, email:1, ssn: 1})
Executing Query
1. Scoring query plan: IXSCAN { birthday: 1, snn: 1 } planHitEOF=0
1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0
noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002)
2. Scoring query plan: IXSCAN { birthday: 1 } planHitEOF=0
1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0
noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002)
3. Scoring query plan: IXSCAN { birthday: -1 } planHitEOF=0
1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0
noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002)
1. Winning plan: IXSCAN { birthday: 1, snn: 1 }
1 1. Relevant index 0 is kp: { birthday: 1.0, snn: 1.0 } name: 'birthday_1_snn_1' io: { v: 2, key: { birthday: 1.0, snn: 1.0
}, name: "birthday_1_snn_1", ns: "test.people" }
2. Relevant index 1 is kp: { birthday: 1.0 } name: 'birthday_1' io: { v: 2, key: { birthday: 1.0 }, name: "birthday_1", ns:
"test.people" }
3. Relevant index 2 is kp: { birthday: -1.0 } name: 'birthday_asc' io: { v: 2, key: { birthday: -1.0 }, name:
"birthday_asc", ns: "test.people" }
MongoDB Execution Plan Scoring
2
3
numWorks
baseScore
common.advanced
workUnits
productivity(Plan Produce range[0, 1])
noFetchBonus
noSortBonus
noIxisectBonus
epsilon
tieBreakers
Scorea
MongoDB Plan Ranking Terms
numWorks - Advanced Work Units
Query Returns 102
document
no of document <= 101YES NO
numWorks = 101
numWorks = no of
document
advanced =
numWorks
works = numWorks
+ 1
advanced =
numWorks
works = numWorks
advanced/wor
kUnits
1
productivity
baseScore
3
noFetchBonus noSortBonus noIxisectBonus
2
Default = 0 or epsilon = std::min(1.0 / static_cast(10 *
workUnits), 1e-4)
tieBreakers Score
ANSWER
Flow Chart
Index Re-build will evict the plan cache
Add or Delete Index will evict the plan cache
The MongoD process restart will evict the plan cache
internalQueryCacheEvictionRatio * _decisionWorks will do
the plan cache eviction
MongoDB Plan Cache - Eviction
internalQueryCacheEvictionRatio: 10.0
_decisionWorks: The number of work cycles taken to decide on
a winning plan when the plan was first
hint()
min()
max()
explain()
snapshot()
Collection scan
Plan Are Not Cached !
db.collection.getPlanCache().listQueryShapes()
db.collection.getPlanCache().clearPlansByQuery()
db.collection.getPlanCache().getPlansByQuery()
db.collection.getPlanCache().clear()
Command To Manage DB Plan Cache
QUESTIONS ?
Thank You

More Related Content

What's hot

Sharding Methods for MongoDB
Sharding Methods for MongoDBSharding Methods for MongoDB
Sharding Methods for MongoDB
MongoDB
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략
Jin wook
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
MongoDB
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
MongoDB
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
Mydbops
 
Retail referencearchitecture productcatalog
Retail referencearchitecture productcatalogRetail referencearchitecture productcatalog
Retail referencearchitecture productcatalog
MongoDB
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
Puneet Behl
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at Scale
MongoDB
 
Mongo DB
Mongo DB Mongo DB
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
Sigit52
 
MongoDB
MongoDBMongoDB
Moving from SQL Server to MongoDB
Moving from SQL Server to MongoDBMoving from SQL Server to MongoDB
Moving from SQL Server to MongoDB
Nick Court
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
Douglas Duncan
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
MongoDB
 
An Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDBAn Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDB
MongoDB
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
Caserta
 
Product catalog using MongoDB
Product catalog using MongoDBProduct catalog using MongoDB
Product catalog using MongoDB
Vishwas Bhagath
 
Elasticsearch development case
Elasticsearch development caseElasticsearch development case
Elasticsearch development case
일규 최
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
Bishal Khanal
 

What's hot (20)

Sharding Methods for MongoDB
Sharding Methods for MongoDBSharding Methods for MongoDB
Sharding Methods for MongoDB
 
Indexing
IndexingIndexing
Indexing
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
 
MongoDB Fundamentals
MongoDB FundamentalsMongoDB Fundamentals
MongoDB Fundamentals
 
MongoDB performance
MongoDB performanceMongoDB performance
MongoDB performance
 
Retail referencearchitecture productcatalog
Retail referencearchitecture productcatalogRetail referencearchitecture productcatalog
Retail referencearchitecture productcatalog
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
MongoDB at Scale
MongoDB at ScaleMongoDB at Scale
MongoDB at Scale
 
Mongo DB
Mongo DB Mongo DB
Mongo DB
 
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
 
MongoDB
MongoDBMongoDB
MongoDB
 
Moving from SQL Server to MongoDB
Moving from SQL Server to MongoDBMoving from SQL Server to MongoDB
Moving from SQL Server to MongoDB
 
MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329MongoDB and Indexes - MUG Denver - 20160329
MongoDB and Indexes - MUG Denver - 20160329
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
An Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDBAn Enterprise Architect's View of MongoDB
An Enterprise Architect's View of MongoDB
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
Product catalog using MongoDB
Product catalog using MongoDBProduct catalog using MongoDB
Product catalog using MongoDB
 
Elasticsearch development case
Elasticsearch development caseElasticsearch development case
Elasticsearch development case
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 

Similar to Introduction to Mongodb execution plan and optimizer

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
yazidds2
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
Bartosz Konieczny
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
MongoDB
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
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
 
query_tuning.pdf
query_tuning.pdfquery_tuning.pdf
query_tuning.pdf
ssuserf99076
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
BizTalk360
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdf
Eric Xiao
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
TAISEEREISA
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
TechWell
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
Chris Baynes
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
Biju Thomas
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
Shahzad
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon)
Doyun Hwang
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
Swapnil Kale
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
MariaDB plc
 

Similar to Introduction to Mongodb execution plan and optimizer (20)

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and Evaluation
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
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
 
query_tuning.pdf
query_tuning.pdfquery_tuning.pdf
query_tuning.pdf
 
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-FunctionsIntegration-Monday-Stateful-Programming-Models-Serverless-Functions
Integration-Monday-Stateful-Programming-Models-Serverless-Functions
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdf
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Pl sql using_xml
Pl sql using_xmlPl sql using_xml
Pl sql using_xml
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Score (smart contract for icon)
Score (smart contract for icon) Score (smart contract for icon)
Score (smart contract for icon)
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
What's New in MariaDB Server 10.2 and MariaDB MaxScale 2.1
 

More from Mydbops

Efficient MySQL Indexing and what's new in MySQL Explain
Efficient MySQL Indexing and what's new in MySQL ExplainEfficient MySQL Indexing and what's new in MySQL Explain
Efficient MySQL Indexing and what's new in MySQL Explain
Mydbops
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
Mydbops
 
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
Mydbops
 
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
Mydbops
 
Mastering Aurora PostgreSQL Clusters for Disaster Recovery
Mastering Aurora PostgreSQL Clusters for Disaster RecoveryMastering Aurora PostgreSQL Clusters for Disaster Recovery
Mastering Aurora PostgreSQL Clusters for Disaster Recovery
Mydbops
 
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Mydbops
 
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
Mydbops
 
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE EventData-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
Mydbops
 
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
Mydbops
 
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
Mydbops
 
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
Mydbops
 
Data Organisation: Table Partitioning in PostgreSQL
Data Organisation: Table Partitioning in PostgreSQLData Organisation: Table Partitioning in PostgreSQL
Data Organisation: Table Partitioning in PostgreSQL
Mydbops
 
Navigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
Navigating MongoDB's Queryable Encryption for Ultimate Security - MydbopsNavigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
Navigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
Mydbops
 
Data High Availability With TIDB
Data High Availability With TIDBData High Availability With TIDB
Data High Availability With TIDB
Mydbops
 
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
Mydbops
 
Enhancing Security of MySQL Connections using SSL certificates
Enhancing Security of MySQL Connections using SSL certificatesEnhancing Security of MySQL Connections using SSL certificates
Enhancing Security of MySQL Connections using SSL certificates
Mydbops
 
Exploring the Fundamentals of YugabyteDB - Mydbops
Exploring the Fundamentals of YugabyteDB - Mydbops Exploring the Fundamentals of YugabyteDB - Mydbops
Exploring the Fundamentals of YugabyteDB - Mydbops
Mydbops
 
Time series in MongoDB - Mydbops
Time series in MongoDB - Mydbops Time series in MongoDB - Mydbops
Time series in MongoDB - Mydbops
Mydbops
 
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - MydbopsTiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
Mydbops
 
Achieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQLAchieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQL
Mydbops
 

More from Mydbops (20)

Efficient MySQL Indexing and what's new in MySQL Explain
Efficient MySQL Indexing and what's new in MySQL ExplainEfficient MySQL Indexing and what's new in MySQL Explain
Efficient MySQL Indexing and what's new in MySQL Explain
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
PostgreSQL Schema Changes with pg-osc - Mydbops @ PGConf India 2024
 
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
Choosing the Right Database: Exploring MySQL Alternatives for Modern Applicat...
 
Mastering Aurora PostgreSQL Clusters for Disaster Recovery
Mastering Aurora PostgreSQL Clusters for Disaster RecoveryMastering Aurora PostgreSQL Clusters for Disaster Recovery
Mastering Aurora PostgreSQL Clusters for Disaster Recovery
 
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
Navigating Transactions: ACID Complexity in Modern Databases- Mydbops Open So...
 
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
AWS RDS in MySQL 2023 Vinoth Kanna @ Mydbops OpenSource Database Meetup 15
 
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE EventData-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
Data-at-scale-with-TIDB Mydbops Co-Founder Kabilesh PR at LSPE Event
 
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
MySQL Transformation Case Study: 80% Cost Savings & Uninterrupted Availabilit...
 
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
Scaling-MongoDB-with-Horizontal-and-Vertical-Sharding Mydbops Opensource Data...
 
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
Mastering MongoDB Atlas: Essentials of Diagnostics and Debugging in the Cloud...
 
Data Organisation: Table Partitioning in PostgreSQL
Data Organisation: Table Partitioning in PostgreSQLData Organisation: Table Partitioning in PostgreSQL
Data Organisation: Table Partitioning in PostgreSQL
 
Navigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
Navigating MongoDB's Queryable Encryption for Ultimate Security - MydbopsNavigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
Navigating MongoDB's Queryable Encryption for Ultimate Security - Mydbops
 
Data High Availability With TIDB
Data High Availability With TIDBData High Availability With TIDB
Data High Availability With TIDB
 
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
Mastering Database Migration_ Native replication (8.0) to InnoDB Cluster (8.0...
 
Enhancing Security of MySQL Connections using SSL certificates
Enhancing Security of MySQL Connections using SSL certificatesEnhancing Security of MySQL Connections using SSL certificates
Enhancing Security of MySQL Connections using SSL certificates
 
Exploring the Fundamentals of YugabyteDB - Mydbops
Exploring the Fundamentals of YugabyteDB - Mydbops Exploring the Fundamentals of YugabyteDB - Mydbops
Exploring the Fundamentals of YugabyteDB - Mydbops
 
Time series in MongoDB - Mydbops
Time series in MongoDB - Mydbops Time series in MongoDB - Mydbops
Time series in MongoDB - Mydbops
 
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - MydbopsTiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
TiDB in a Nutshell - Power of Open-Source Distributed SQL Database - Mydbops
 
Achieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQLAchieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQL
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 

Introduction to Mongodb execution plan and optimizer

  • 2. Interested in Open Source technologies Active MongoDB Community Contributor Tech Speaker/Blogger Senior DevOps and MongoDB Consultant Manosh Malai About Me
  • 4. 250 + Clients In 3 Yrs. of Operations Our Clients
  • 5. MongoDB Execution Plan Analysis MongoDB Optimizer and Plan Cache Query in the MongoDB Execution Layer Agenda
  • 6. Query In The MongoDB Execution Layer Client net listener thread_conn Query Decode Operation Context Catalog MapLayer Canonical Plan Plan Executor Optimizer RecordStore & Cursor Snapshot
  • 7. A client connects to MongoDB and creates a new thread to handle all requests. Some Query(Such as insert) does not need to execute the plan, It will directly interact with the engine through RecordStore. Query performs simple processing (standardization) and builds some context data structures into CanonicalQuery. The Plan module is qualified for generating multiple execution plans for the Query, then delivering it to the Optimizer to select the best one and surrendering it to the PlanExecutor. PlanExecutor step by step according to the execution plan to obtain the final data (or perform the update to modify the data). Query Statement Execution Algorithm
  • 8. Current version of Explain has three mode: queryPlanner executionStats allPlansExecution db.collection.find().explain() Execution Plan Analysis MongoDB Execution Plan Analysis
  • 9. queryPlanner is the default mode of the current version of explain. The queryPlanner mode does not actually query the query statement. Performs an execution plan analysis for the query statement and selects the winning plan. queryPlanner.winningPlan.stage: COLLSCAN Without Index queryPlanner.winningPlan.stage: FETCH With Index queryPlanner Mode
  • 10. queryPlanner + executionStats information of the evaluated query. With Index explain.queryPlanner.indexFilterSet explain.queryPlanner.winningPlan.stage explain.executionStats.nReturned explain.executionStats.executionTimeMillis explain.executionStats.totalKeysExamined explain.executionStats.totalDocsExamined explain.executionStats.executionStages.advanced explain.executionStats.executionStages.works explain.executionStats.executionStages.inputStage.docsExamined explain.executionStats.executionStages.isEOF executionStats Mode
  • 11. EX db.runCommand( { planCacheSetFilter: "orders", query: { status: "A" }, indexes: [ { cust_id: 1, status: 1 }, { status: 1, order_date: -1 } ] } ) IndexFilter determines how the query optimizer will use index for a type of query. Thquery optimizer will ignore the index set by the 1. explain.queryPlanner.indexFilterSet The stage of the optimal execution plan 2. explain.queryPlanner.winningPlan.stage COLLSCAN: Full table scan IXSCAN: Index scan FETCH: Retrieve the specified document based on the indexEmpty text SHARD_MERGE: Return each fragment to the data for merge SORT: Indicates that sorting is done in memor LIMIT: Use limit to limit the number of returns SKIP: Skip using skip IDHACK: Query for _id SHARDING_FILTER: Querying fragmented data by mongos COUNT: Count operation using db.coll.explain().count() COUNTSCAN: Count does not use the stage return when using Count for index COUNT_SCAN: Count uses the stage to return when the index is counted SUBPLA: Stage return of $or query not used to index TEXT: Stage return when using full-text index for queryPROJECTION: The return of the stage when the return field is qualified STAGE executionStats Metrics
  • 12. executionStats Metrics The number of returns returned by the query  3. explain.executionStats.nReturned Overall execution time 4. explain.executionStats.executionTimeMillis Number of index scans 5. explain.executionStats.totalKeysExamined Document scans 6. explain.executionStats.totalDocsExamined
  • 13. executionStats.inputStage Metrics 8. explain.executionStats.executionStages.works 7. explain.executionStats.executionStages.advanced 9. explain.executionStats.executionStage.isEOF
  • 14. The planner ask plan each time for the next document via call to work() If the plan can give supply document it respond with document, Otherwise the plan respond with needTime If all the all the document have been retrieved then isEOF = 1 Work - Advanced - isEOF [ Algorithm ] "works": 18667 "advanced": 18666 "needTime": 0
  • 15. WorkingSet workingSet; PlanStage* rootStage = makeQueryPlan(&workingSet, ...); while (!rootStage->isEOF()) { WorkingSetID result; switch(rootStage->work(&result)) { case PlanStage::ADVANCED: // do something with result WorkingSetMember* member = workingSet.get(result); cout << "Result: " << member->obj << std::endl; break; case PlanStage::IS_EOF: // All done. Will fall out of while loop. break; Work - Advanced - isEOF [ Code ] Cont . . case PlanStage::NEED_TIME: // Need more time. break; case PlanStage::FAILURE: // Throw exception or return error. break; } if (shouldYield) { // Occasionally yield. stage->saveState(); stage->restoreState(); } }
  • 16. As the name suggests, the allPlanExxecution mode is to perform all execution plans in the executionStats mode. It will show all candidate Rejected Plans. allPlansExecution Mode
  • 17. Plan Optimizer and Plan Cache
  • 18. Find Matching Cache Entry Empty text Evaluate Plan Performance Generate Candidate Plans Query Empty text Evaluate Candidate Plans Choose Winning Plans Create Cache Entry Generate Result Documents Evict Cache Entry NO MATCH MATCH FAIL PASS Plan Optimiser
  • 19. QueryPlanner Canonical Query Canonical Query * No of Indexes based on predicate Conditions = Candidate Plane Select a Wining Plane and Add it Plane Cache Ranking the Candidate Plane
  • 20. db.setLogLevel(2,'query') db.people.getPlanCache().clear() db.people.find({"birthday": { $gte: new ISODate("2016-03-22T11:34:15Z")}}, {first_name:1, birthday:1, employer:1, email:1, ssn: 1}) Executing Query
  • 21. 1. Scoring query plan: IXSCAN { birthday: 1, snn: 1 } planHitEOF=0 1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0 noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002) 2. Scoring query plan: IXSCAN { birthday: 1 } planHitEOF=0 1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0 noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002) 3. Scoring query plan: IXSCAN { birthday: -1 } planHitEOF=0 1. score(2.0002) = baseScore(1) + productivity((101 advanced)/(101 works) = 1) + tieBreakers(0 noFetchBonus + 0.0001 noSortBonus + 0.0001 noIxisectBonus = 0.0002) 1. Winning plan: IXSCAN { birthday: 1, snn: 1 } 1 1. Relevant index 0 is kp: { birthday: 1.0, snn: 1.0 } name: 'birthday_1_snn_1' io: { v: 2, key: { birthday: 1.0, snn: 1.0 }, name: "birthday_1_snn_1", ns: "test.people" } 2. Relevant index 1 is kp: { birthday: 1.0 } name: 'birthday_1' io: { v: 2, key: { birthday: 1.0 }, name: "birthday_1", ns: "test.people" } 3. Relevant index 2 is kp: { birthday: -1.0 } name: 'birthday_asc' io: { v: 2, key: { birthday: -1.0 }, name: "birthday_asc", ns: "test.people" } MongoDB Execution Plan Scoring 2 3
  • 22. numWorks baseScore common.advanced workUnits productivity(Plan Produce range[0, 1]) noFetchBonus noSortBonus noIxisectBonus epsilon tieBreakers Scorea MongoDB Plan Ranking Terms
  • 23. numWorks - Advanced Work Units Query Returns 102 document no of document <= 101YES NO numWorks = 101 numWorks = no of document advanced = numWorks works = numWorks + 1 advanced = numWorks works = numWorks
  • 24. advanced/wor kUnits 1 productivity baseScore 3 noFetchBonus noSortBonus noIxisectBonus 2 Default = 0 or epsilon = std::min(1.0 / static_cast(10 * workUnits), 1e-4) tieBreakers Score ANSWER Flow Chart
  • 25. Index Re-build will evict the plan cache Add or Delete Index will evict the plan cache The MongoD process restart will evict the plan cache internalQueryCacheEvictionRatio * _decisionWorks will do the plan cache eviction MongoDB Plan Cache - Eviction internalQueryCacheEvictionRatio: 10.0 _decisionWorks: The number of work cycles taken to decide on a winning plan when the plan was first