SlideShare a Scribd company logo
1 of 28
Download to read offline
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

Reading the .explain() Output
Reading the .explain() OutputReading the .explain() Output
Reading the .explain() OutputMongoDB
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation FrameworkCaserta
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리Junyi Song
 
Deep Dive Into Elasticsearch
Deep Dive Into ElasticsearchDeep Dive Into Elasticsearch
Deep Dive Into ElasticsearchKnoldus Inc.
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuningelliando dias
 
Kafka Connect - debezium
Kafka Connect - debeziumKafka Connect - debezium
Kafka Connect - debeziumKasun Don
 
MongoDB Aggregation Performance
MongoDB Aggregation PerformanceMongoDB Aggregation Performance
MongoDB Aggregation PerformanceMongoDB
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Jin wook
 
Mongodb Aggregation Pipeline
Mongodb Aggregation PipelineMongodb Aggregation Pipeline
Mongodb Aggregation Pipelinezahid-mian
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]MongoDB
 
Moving from SQL Server to MongoDB
Moving from SQL Server to MongoDBMoving from SQL Server to MongoDB
Moving from SQL Server to MongoDBNick Court
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Jimmy Lai
 
An introduction to Elasticsearch's advanced relevance ranking toolbox
An introduction to Elasticsearch's advanced relevance ranking toolboxAn introduction to Elasticsearch's advanced relevance ranking toolbox
An introduction to Elasticsearch's advanced relevance ranking toolboxElasticsearch
 

What's hot (20)

Reading the .explain() Output
Reading the .explain() OutputReading the .explain() Output
Reading the .explain() Output
 
MongoDB Aggregation Framework
MongoDB Aggregation FrameworkMongoDB Aggregation Framework
MongoDB Aggregation Framework
 
elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리elasticsearch_적용 및 활용_정리
elasticsearch_적용 및 활용_정리
 
Indexes in postgres
Indexes in postgresIndexes in postgres
Indexes in postgres
 
Deep Dive Into Elasticsearch
Deep Dive Into ElasticsearchDeep Dive Into Elasticsearch
Deep Dive Into Elasticsearch
 
Indexing
IndexingIndexing
Indexing
 
MongodB Internals
MongodB InternalsMongodB Internals
MongodB Internals
 
PostgreSQL Performance Tuning
PostgreSQL Performance TuningPostgreSQL Performance Tuning
PostgreSQL Performance Tuning
 
An introduction to MongoDB
An introduction to MongoDBAn introduction to MongoDB
An introduction to MongoDB
 
Kafka Connect - debezium
Kafka Connect - debeziumKafka Connect - debezium
Kafka Connect - debezium
 
MongoDB Aggregation Performance
MongoDB Aggregation PerformanceMongoDB Aggregation Performance
MongoDB Aggregation Performance
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략
 
Mongodb Aggregation Pipeline
Mongodb Aggregation PipelineMongodb Aggregation Pipeline
Mongodb Aggregation Pipeline
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
 
Introduction to Amazon DynamoDB
Introduction to Amazon DynamoDBIntroduction to Amazon DynamoDB
Introduction to Amazon DynamoDB
 
Moving from SQL Server to MongoDB
Moving from SQL Server to MongoDBMoving from SQL Server to MongoDB
Moving from SQL Server to MongoDB
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...
 
PostgreSQL: Advanced indexing
PostgreSQL: Advanced indexingPostgreSQL: Advanced indexing
PostgreSQL: Advanced indexing
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
An introduction to Elasticsearch's advanced relevance ranking toolbox
An introduction to Elasticsearch's advanced relevance ranking toolboxAn introduction to Elasticsearch's advanced relevance ranking toolbox
An introduction to Elasticsearch's advanced relevance ranking toolbox
 

Similar to Introduction to Mongodb execution plan and optimizer

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
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 customizationBartosz Konieczny
 
Webinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationWebinar: Index Tuning and Evaluation
Webinar: Index Tuning and EvaluationMongoDB
 
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 TricksMongoDB
 
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
 
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-FunctionsBizTalk360
 
Write Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfWrite Faster SQL with Trino.pdf
Write Faster SQL with Trino.pdfEric 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 iOSTechWell
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteChris Baynes
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - PresentationBiju 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
 
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.pptSwapnil 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.1MariaDB 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

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 RouterMydbops
 
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 2024Mydbops
 
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 RecoveryMydbops
 
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 15Mydbops
 
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 EventMydbops
 
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 PostgreSQLMydbops
 
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 - MydbopsMydbops
 
Data High Availability With TIDB
Data High Availability With TIDBData High Availability With TIDB
Data High Availability With TIDBMydbops
 
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 certificatesMydbops
 
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 - MydbopsMydbops
 
Achieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQLAchieving High Availability in PostgreSQL
Achieving High Availability in PostgreSQLMydbops
 
Scaling MongoDB with Horizontal and Vertical Sharding
Scaling MongoDB with Horizontal and Vertical Sharding Scaling MongoDB with Horizontal and Vertical Sharding
Scaling MongoDB with Horizontal and Vertical Sharding Mydbops
 

More from Mydbops (20)

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
 
Scaling MongoDB with Horizontal and Vertical Sharding
Scaling MongoDB with Horizontal and Vertical Sharding Scaling MongoDB with Horizontal and Vertical Sharding
Scaling MongoDB with Horizontal and Vertical Sharding
 

Recently uploaded

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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