Lab-MongoDB Index

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Lab: MongoDB Index

Version Nov 24, 2022

Create the following inventory collection. Make sure to delete the existing documents before.

db.inventory.insertMany( [
{ item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
{ item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
{ item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
])

1. Check index using the following command


db.inventory.getIndexes()

The expression "v" : 2 in the result means version 2.

2. Create a single key index


db.inventory.createIndex( { item: -1 } )

You may use the command db.inventory.getIndexes() to check the indexes again.

Drop the index by the expression


db.inventory.dropIndex( { item: -1 } )

Or drop the index by name


db.inventory.dropIndex( "item_-1" )

3. Run the following command to check the execution plan


db.inventory.explain("executionStats").find( { qty: { $gt: 80 } }, { item: 1, qty: 1, _id: 0 } )
Before creating a compound index, need to examine all 10 documents.

4. Creating a compound index

db.inventory.createIndex(
{ qty: 1, item: 1 } ,
{ name: "idx_qty_item" }
)
After creating the compound index, only need to examine 4 documents.

Drop index by name


db.inventory.dropIndex( "idx_qty_item" )
5. Covered queries or covering indexes

MongoDB also has the concept of covered queries or covering indexes.

“When the query criteria and the projection of a query include only the indexed fields,
MongoDB returns results directly from the index without scanning any documents or
bringing documents into memory. These covered queries can be very efficient.”

Question: is the previous query covered by the index idx_qty_item?


db.inventory.find( { qty: { $gt: 80 } }, { item: 1, qty: 1, _id: 0 } )

How about the following query?


db.inventory.find( { item: /^p/ }, { item: 1, qty: 1, _id: 0 } )

https://www.mongodb.com/docs/manual/indexes/
https://www.mongodb.com/docs/manual/core/query-optimization/#std-label-read-
operations-covered-query

The course materials are only for the use of students enrolled in the course CSIS 3300 at Douglas
College. Sharing this material to a third-party website can lead to a violation of Copyright law.

You might also like