March 2019
Intermediate to advanced
394 pages
11h 4m
English
The order of indexing is useful for sorting results. In single field indexes, MongoDB can traverse the index both ways, so it doesn't matter which order we define.
In multi-field indexes, however, ordering can determine whether we can use this index to sort. In the preceding example, a query matching the sort direction of our index creation will use our index as follows:
> db.books.find().sort( { "name": 1, "isbn": 1 })
It will also use a sort query with all of the sort fields reversed:
> db.books.find().sort( { "name": -1, "isbn": -1 })
In this query, since we negated both of the fields, MongoDB can use the same index, traversing it from the end to the start.
The other two sorting orders are as follows:
> db.books.find().sort( ...
Read now
Unlock full access