Consider a MongoDB collection with a compound index on { age: 1, score: -1 }. Which query will efficiently use this index?
db.collection.find({ age: 25, score: { $gte: 80 } })Think about how MongoDB uses the prefix of the compound index fields in order.
MongoDB uses the compound index starting from the first field. Since the query filters on age first and then on score, it can use the index efficiently.
Why does the order of fields in a MongoDB compound index matter?
Think about how indexes are structured and how queries match them.
The order matters because MongoDB uses the index starting from the first field. If a query does not filter on the first field(s), the index cannot be used efficiently.
Which of the following commands correctly creates a compound index on lastName ascending and age descending in MongoDB?
Remember the syntax for createIndex uses a single object with field names and directions.
The correct syntax uses a single object with field names as keys and 1 or -1 as values to indicate ascending or descending order.
You have a compound index on { city: 1, status: 1 }. Which query will NOT use this index efficiently?
Options:
A) db.collection.find({ city: "NY", status: "active" })
B) db.collection.find({ status: "active" })
C) db.collection.find({ city: "NY" })
D) db.collection.find({ city: "NY", status: { $in: ["active", "pending"] } })Recall that the index can only be used efficiently if the query filters on the first field in the index.
Since the index starts with city, queries filtering only on status cannot use the index efficiently.
A MongoDB collection has a compound index on { category: 1, price: 1 }. A query db.products.find({ price: { $lt: 100 } }) is slow and does not use the index. Why?
Think about how MongoDB uses compound indexes and the importance of filtering on the first field.
MongoDB requires queries to filter on the first field of a compound index to use it efficiently. Since the query filters only on price (second field), the index is not used.