Indexing Flashcards
What is an index and what is its purpose?
An index is a B-tree of sorted field values that point to documents in the collection. Each node stores a field value that points to the actual document in the collection. Its purpose is to improve query performance
True or False
Without indexes, MongoDB needs to read all documents in a collection when data is queried
True
True or False
When indexes are used, MongoDB FETCH
s the appropriate documents from the collection instead of performing an COLLSCAN
True
By default, what index is created when a collection is created?
Can it be deleted?
An _id
index is created
No
What are the pros and cons of indexes?
Pros:
* Faster reads since the entire collection need not be traversed
* Faster reads since its values are sorted O(logn)
Cons:
* Slower writes since the values must also be added to the index (1 write for the actual document and 1 write for the index)
What are the 4 different index types?
- Single-field index
- Single-field multikey index
- Compound index
- Compound multikey index
What is a single-field index?
A single-field index is an index with one field
What is a single-field multikey index?
A single-field multikey index is an index with one field that is an array
What is a compound index?
A compound index is an index with multiple fields
What is a compound multikey index?
A compound multikey index is an index with multiple fields and one of those fields is an array
True or False
When using a multikey index, each element in the array gets an index key
True
Code an example of creating a single-field index where the field is unique in mongosh
db.collection.createIndex({field: 1 or -1}, {unique: true})
Code an example of creating a single-field multikey index in mongosh
db.collection.createIndex({fieldArr: 1 or -1})
Code an example of getting the indexes in a collection
db.collection.getIndexes()
Code an example analyzing whether an index is being used for a read operation
db.collection.explain().find(...)
Describe the differences between COLLSCAN
, FETCH
, and IXSCAN
- COLLSCAN implies a full collection scan (no indexes are used)
- FETCH implies retrieving documents (not a full collection scan)
- IXSCAN implies scanning index keys
True or False
Multikey indexes can have multiple field arrays
False. Multikey indexes can only have 1 field array
What are the queries that can be supported by the following compound index:
db.collection.createIndex({item: 1, location: 1, stock: 1})
find({item: value}) find({item: value, location: value}) find({item: value, location: value, stock: value})
When creating indexes, what field order does MongoDB recommend?
- Equality fields
- Sort fields
- Range fields