Can an index {birthday: -1, name: 1} be used on a bd.collection.sort({birthday: 1, name: -1})?

Prepare for the MongoDB Associate Developer Exam with flashcards and practice multiple choice questions. Each question includes hints and explanations to ensure you're ready for test day.

The index defined as {birthday: -1, name: 1} can be utilized for queries that sort on birthday in ascending order and name in descending order, even though the sort order of the index and the sort order in the query are different. This is because MongoDB can utilize the existing index to optimize the sorting operation.

When a query is sorted, MongoDB will look for an index that can support the sort operation. The significant aspect here is that MongoDB can use the index to support the sorting of fields in either ascending or descending order. In this case, although the birthday field in the index is sorted in descending order (-1) and the query requests it in ascending order (1), MongoDB still recognizes that a partial match can be used. Specifically, the birthday index can be leveraged to access the records faster, even if it requires inverting the sort order of that field during retrieval.

Thus, the ability to access the data efficiently from this index makes it applicable to this query despite the differing sort orders. With this understanding, the assertion that the index can be used is validated.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy