Given a query with a predicate and sort over the same field, and given a document where this field is an array, it is expected that the sort key generated for the document will be the first element in the array that is within the bounds specified by the predicate (or last element in the array, if a descending sort is requested). The merge sort for sharded queries does not choose sort keys this way; the entire array is incorrectly chosen as the sort key.
Example: suppose that "foo" is a sharded collection over two shards, and each shard contains one document.
mongos> db.foo.find().sort({a:1}) { "_id" : -1, "a" : [ 3, 5 ] } { "_id" : 0, "a" : [ 4 ] } mongos> db.foo.find({a:{$gt:3}}).sort({a:1}) // results in wrong order { "_id" : -1, "a" : [ 3, 5 ] } { "_id" : 0, "a" : [ 4 ] }
The results for the second query above are in the incorrect order. The sort key for {_id: -1} should be "5", and the sort key for {_id:0} should be "4".
On "bar", an unsharded collection with the same data, the results appear in the correct order.
mongos> db.bar.find().sort({a:1}) { "_id" : -1, "a" : [ 3, 5 ] } { "_id" : 0, "a" : [ 4 ] } mongos> db.bar.find({a:{$gt:3}}).sort({a:1}) // results in correct order { "_id" : 0, "a" : [ 4 ] } { "_id" : -1, "a" : [ 3, 5 ] }
- is related to
-
SERVER-13426 weird $sort behavior
- Closed
-
SERVER-19394 Results in incorrect order for query with bounded sort on multi-key field when SORT_MERGE plan used
- Closed
-
SERVER-19397 Results in incorrect order for complex $or query with bounded sort on multi-key field when SORT plan used
- Closed
-
SERVER-19402 Change semantics of sorting by array fields in find and aggregate
- Closed
- related to
-
SERVER-8146 sort by array element is incorrect under sharding environment
- Closed