M101J: MongoDB for Java Developers Homework 4.1
This HomeWork is related to find which query will be using index to get result.
you can use query to find list of index
db.system.indexes.find()
Document:
This HomeWork is related to find which query will be using index to get result.
you can use query to find list of index
db.system.indexes.find()
Document:
{ "v" : 1, "key" : { "sku" : 1 }, "unique" : true, "ns" : "store.products", "name" : "sku_1" }
Key Indicates there exist an index sku on collection products with index name as
sku_1.[at the time of index creation if we give {sku:-1} name of index will be
sku_-1]
db.collectionname.getIndexes() can be used to get index in individual collection
Now lets complete the homework.
Which of the following queries can utilize an index. Check all that apply.
1) db.products.find({'brand':"GE"})
if you check in document , there is no index with brand, you will find brand
index as multi index with category. but in query we are only using brand so above
query cannot utilize and index.
2)db.products.find({'brand':"GE"}).sort({price:1})
if you check in document, you will see brand cannot use an index, but in document
if you see price is present as single index. so the above query use an index.
3)db.products.find({$and:[{price:{$gt:30}},{price:{$lt:50}}]}).sort({brand:1})
price is present, therefore query is using index.
4) db.products.find({brand:'GE'}).sort({category:1, brand:-1}).explain()
category and brand are present in document as multi - index but if you check
index is created with {category:1, brand:1} but while using in query it is using
{category:1, brand:-1}, so for sorting mongo will perform complete scan and
it will not use index . if index was created with {category:1, brand:-1} then
the above query will be using an index.
So your homework 4.1 answer is
No comments:
Post a Comment