If a collection contains:
{} {a: 1} {a: []} {a: [1]} {a: [0, 1]}
... there are some bizarre semantics for how it's sorted. The empty array comes before the absence-of-a-field, and "1" comes between [0, 1] and [1]:
> db.collection.find({}, {_id: false}).sort({a: 1}) { "a" : [ ] } { } { "a" : [ 0, 1 ] } { "a" : 1 } { "a" : [ 1 ] }
Reversing the sort does not quite reverse the order of results:
> db.collection.find({}, {_id: false}).sort({a: -1}) { "a" : 1 } { "a" : [ 1 ] } { "a" : [ 0, 1 ] } { } { "a" : [ ] }
There are a number of tickets, some incomplete, regarding this confusing behavior:
- is related to
-
SERVER-11444 $lt/$lte/$gte/$gt behaves differently with array operand
- Closed