Files
mongo/jstests/aggregation/unwind_sort.js
Ivan Fefer 2c9d603974 SERVER-90485 Fix $sort on fields, produced by $unwind (#22290)
### Issue

SERVER-90485

### Description

$unwind has an optimization to push $sort in front of it, if possible.
This optimization incorrectly pushed $sort down if it was performed on
array index field, generated by $unwind.

Replaced bidirectionalPathPrefixOf with ModPaths.canModify. It was the
only usage of this function, so I removed it.

### Testing

https://spruce.mongodb.com/version/664757ec5cd24f0007f22bd5/tasks

GitOrigin-RevId: 14050193ffb2e3381763e0cbeb88065d0d37cfce
2024-05-21 12:39:18 +00:00

28 lines
1.0 KiB
JavaScript

// Test that we can sort on fields, produces by unwind
const coll = db.agg_unwind_sort;
coll.drop();
assert.commandWorked(coll.insertOne({a: [3, 4, 5]}));
assert.commandWorked(coll.insertOne({a: [1, 2]}));
let result = coll.aggregate([{$unwind: "$a"}, {$sort: {a: 1}}]).toArray();
assert.eq([1, 2, 3, 4, 5], result.map(function(z) {
return z.a;
}));
result = coll.aggregate([{$unwind: "$a"}, {$sort: {a: -1}}]).toArray();
assert.eq([5, 4, 3, 2, 1], result.map(function(z) {
return z.a;
}));
result =
coll.aggregate([{$unwind: {path: "$a", includeArrayIndex: "i"}}, {$sort: {i: 1}}]).toArray();
assert.eq([NumberLong(0), NumberLong(0), NumberLong(1), NumberLong(1), NumberLong(2)],
result.map(function(z) {
return z.i;
}));
result =
coll.aggregate([{$unwind: {path: "$a", includeArrayIndex: "i"}}, {$sort: {i: -1}}]).toArray();
assert.eq([NumberLong(2), NumberLong(1), NumberLong(1), NumberLong(0), NumberLong(0)],
result.map(function(z) {
return z.i;
}));