MongoDB MongoDB Indexing and Performance 1 — Questions and Answers
Question 1: What is the default index created automatically on every MongoDB collection?
- A compound index on all fields
- A text index on the name field
- A unique index on the _id field (Correct answer)
- A sparse index on null fields
Correct answer: A unique index on the _id field
MongoDB automatically creates a unique index on the _id field for every collection, which cannot be dropped.
Question 2: Which method creates an index on a MongoDB collection?
- collection.addIndex()
- collection.createIndex() (Correct answer)
- collection.buildIndex()
- collection.newIndex()
Correct answer: collection.createIndex()
createIndex() creates an index on the specified field(s) with the given options, or returns the existing index name if it already exists.
Question 3: What does a compound index in MongoDB index?
- Multiple collections simultaneously
- A single field with multiple data types
- Multiple fields within a single index (Correct answer)
- Compressed and uncompressed versions of a field
Correct answer: Multiple fields within a single index
A compound index includes references to multiple fields, supporting queries that filter or sort on those fields in the specified order.
Question 4: What is a sparse index in MongoDB?
- An index with gaps between entries
- An index that only includes documents where the indexed field exists (Correct answer)
- An index on sparsely populated collections
- A partial index on every other document
Correct answer: An index that only includes documents where the indexed field exists
A sparse index only contains entries for documents that have the indexed field, skipping documents where the field is absent.
Question 5: Which explain() verbosity mode shows the winning query plan and execution statistics?
- 'queryPlanner'
- 'executionStats' (Correct answer)
- 'allPlansExecution'
- 'verbose'
Correct answer: 'executionStats'
'executionStats' mode returns statistics about the winning plan's execution, including documents examined and time taken.
Question 6: What does the hint() cursor method do in MongoDB?
- Provides query optimization hints to developers
- Forces MongoDB to use a specific index for the query (Correct answer)
- Adds hints to the query explanation
- Hints at which documents will be returned
Correct answer: Forces MongoDB to use a specific index for the query
hint() overrides MongoDB's query optimizer and forces use of the specified index, which can be specified by name or key pattern.
What is the default index created automatically on every MongoDB collection?