Database Reference
In-Depth Information
query
=
query
.
sort
([
(
'details.issue_date'
,
-
1
)])
Inordertosupportthis queryefficiently,we'll create acompound index onthe properties used
in the filter and the sort:
db
.
products
.
ensure_index
([
(
'type'
,
1
),
(
'details.genre'
,
1
),
(
'details.issue_date'
,
-
1
)])
NOTE
The final component of the index is the sort field. This allows MongoDB to traverse the
index in the sorted order and avoid a slow in-memory sort.
Find movies based on starring actor
Another example of a
detail
field-based query would be one that selects films that a partic-
ular actor starred in, sorted by issue date:
query
=
db
.
products
.
find
({
'type'
:
'Film'
,
'details.actor'
:
'Keanu Reeves'
})
query
=
query
.
sort
([(
'details.issue_date'
,
-
1
)])
To support this query, we'll create an index on the fields used in the query:
db
.
products
.
ensure_index
([
(
'type'
,
1
),
(
'details.actor'
,
1
),
(
'details.issue_date'
,
-
1
)])
This index begins with the
type
field and then narrows by the other search field, where the
final component of the index is the sort field to maximize index efficiency.