Sorting array elements is quite complicated. Since the elements of the array are indexed separately, sorting by array field will actually lead to some interesting situations. What happens is that MongoDB will sort them based on the lowest or largest value in the array (depending on the direction of sorting). In addition, the order is natural.
This leads to things like:
> db.test.save({a:[1]}) > db.test.save({a:[0,2]}) > db.test.find().sort({a:1}) { "_id" : ObjectId("4f29026f5b6b8b5fa49df1c3"), "a" : [ 0, 2 ] } { "_id" : ObjectId("4f2902695b6b8b5fa49df1c2"), "a" : [ 1 ] } > db.test.find().sort({a:-1}) { "_id" : ObjectId("4f29026f5b6b8b5fa49df1c3"), "a" : [ 0, 2 ] } { "_id" : ObjectId("4f2902695b6b8b5fa49df1c2"), "a" : [ 1 ] }
In other words. The same order for reverse sorts. This is because the βaβ field of the top document contains both the minimum and highest values.
So effective for sorting MongoDB ignores all values ββin the array that are not either the highest ({field: -1} sort) or the lowest ({field: 1} sort) and orders the remaining values.
To draw a (simplified) picture, it works something like this:
smoothed b-tree for index {a: 1}, above sample documents:
"a" value 0 -> document 4f29026f5b6b8b5fa49df1c3 "a" value 1 -> document 4f2902695b6b8b5fa49df1c2 "a" value 2 -> document 4f29026f5b6b8b5fa49df1c3
As you can see, scanning from top to bottom and from bottom to top will result in the same order.
Empty arrays are the "minimum" possible value of the array and, thus, will be displayed at the top and bottom of the above queries, respectively.
Indexes do not change the sort behavior on arrays.