-
Type: Task
-
Resolution: Done
-
Priority: Minor - P4
-
Affects Version/s: None
-
Labels:
Hi,
On this page we describe the comparison order for different types. For array fields, we say the following:
With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays.
On this page, we say in two places here and here that arrays are sorted according to the first element in the array.
These two pages seem to contradict each other. One seems to say that array fields are sorted by the smallest/largest element and the other seems to say that they are sorted according to the first element.
I've been doing some testing with it and the first page seems to be the correct one. For example:
(This was tested on v5.0.5)
db.foo.insertMany([ {a:[2,{'x':1}]}, {a:[{'x':3},1]} ])
If the sort is on the first element, I would expect the document with 2 as the first element to be sorted first because it's a number and this should be before the other document which has an Object in it's first element according to the comparison order.
However, the sort order is as follows:
> db.foo.find().sort({a:1}) { "_id" : ObjectId("6271639f153ca114c0fd6d74"), "a" : [ { "x" : 3 }, 1 ] } { "_id" : ObjectId("6271639f153ca114c0fd6d73"), "a" : [ 2, { "x" : 1 } ] }
The document with ObjectId 6271639f153ca114c0fd6d74 is sorted first because it's smallest element is 1. If it was being sorted by the first element, it should be second.
This appears to match the way it is described in the Comparison/Sort Order page, but not in the Use Indexes to Sort Query Results page.