WK 2 3 MongoDB Indexing
WK 2 3 MongoDB Indexing
MongoDB Indexing
Objectives
After completing this lab you will be able to:
Measure the time it takes to execute a query with the explain function
Describe the process of creating, listing and deleting indexes
Evaluate the effectiveness of an index
Prerequisites
Before starting this lab, it’ll be helpful to have knowledge about accessing and performing basic operations with MongoDB. If you’re
unfamiliar with MongoDB, feel free to take a look at the Getting Started with MongoDB and MongoDB CRUD labs!
2. Problem:
3. Problem:
4. Problem:
about:blank 1/4
10/3/23, 3:18 PM about:blank
Click here for Solution
1. use training
2. for (i=1;i<=200000;i++){print(i);db.bigdata.insert({"account_no":i,"balance":Math.round(Math.random()*1000000)})}
Copied!
Verify that 200000 documents got inserted by running the below command.
1. 1
1. db.bigdata.count()
Copied!
We will make use of the explain function to find the time taken to run the query in milliseconds.
1. db.bigdata.find({"account_no":58982}).explain("executionStats").executionStats.executionTimeMillis
Copied!
Make a note of the milliseconds it took to run the query. We will need this at a later stage.
1.
2. db.bigdata.createIndex({"account_no":1})
Copied!
Run the below command to get a list of indexes on the ‘bigdata’ collection.
1. 1
1. db.bigdata.getIndexes()
Copied!
about:blank 2/4
10/3/23, 3:18 PM about:blank
1. db.bigdata.find({"account_no": 69271}).explain("executionStats").executionStats.executionTimeMillis
Copied!
Make a note of the milliseconds it took to run the query. Compare this with the time you recored during Exercise-3. This should be a lot less
than that.
1. db.bigdata.dropIndex({"account_no":1})
Copied!
Practice exercises
1. Problem:
1. db.bigdata.createIndex({"balance":1})
Copied!
2. Problem:
Query for documents with a balance of 10000 and record the time taken.
1. db.bigdata.find({"balance":10000}).explain("executionStats").executionStats.executionTimeMillis
Copied!
3. Problem:
about:blank 3/4
10/3/23, 3:18 PM about:blank
1. 1
1. db.bigdata.dropIndex({"balance":1})
Copied!
4. Problem:
Query for documents with a balance of 10000 and record the time taken, and compare it with the previously recorded time.
1. db.bigdata.find({"balance": 10000}).explain("executionStats").executionStats.executionTimeMillis
Copied!
5. Problem:
1. exit
Copied!
Authors
Ramesh Sannareddy
Other Contributors
Rav Ahuja
Change Log
Date (YYYY-MM-DD) Version Changed By Change Description
2021-11-17 0.4 Kathy An Updated lab instructions
2021-04-19 0.3 Steve Ryan Review pass
2021-03-17 0.2 Ramesh Sannareddy Added Hints/Solutions to Practise exercises
2021-02-24 0.1 Ramesh Sannareddy Created initial version of the lab
about:blank 4/4