Link between Project & Sort clauses

Hi,

I have included a field in $Project and a different one in $Sort in aggregate() function. For example,

db.movies.aggregate( [ {$project: {_id:0, title:1, “imdb.rating”:1}},
{$sort: { cast: -1 }
] )

Is there anything wrong with this? My understanding of query execution is, first the list of documents are selected (no match clause here; so the entire set); Second - sorting is done. Finally, whichever fields are mentioned in $project clause are displayed.
Is this okay? I observed that, as sort does not include a field from the $project, the results are varying, I.e.,

db.movies.aggregate( [ {$project: {_id:0, title:1, “imdb.rating”:1, cast:1}},
{$sort: { cast: -1 }
] )

gives a different order of records. Why this is so?
Thank you.

After the project the field cast does not exist anymore. When the sort stage is run there is nothing to sort so the order is undefined. You must project the field you want to sort on.