Cannot sort arrays using unwind or reduce mongodb aggregation pipline

Multi tool use


Cannot sort arrays using unwind or reduce mongodb aggregation pipline
I am having a problem sorting an array in a mongodb aggregation pipeline. I couldn't find an answer in stackoverflow so am posting my problem
I have some data in mongodb which has this structure
{
testOne:{ scores:[1, 5, 8]},
testTwo:{scores:[3, 4, 5]},
testThree:{scores:[9,0,1]},
........
testFifty:{scores:[0,8,1]}
}
Basically a series of many tests and the scores from those tests (this is a simplified example to illustrate the problem).
After a few hours banging my head against a wall I found I could only unwind two arrays, any more and no data was returned.
So I couldn't unwind all my arrays and group to get arrays of each test scores from the db
db.collection.aggregate([
{
{$unwind: '$testOne.scores'},
{$unwind: '$testTwo.scores'},
{$unwind: '$testThree.scores'},
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"},
concatTestTwo: { $push: "$testTwo.scores"},
concatTestThree: { $push: "$testThree.scores"}
}
}
To my frustration , even if I just did one unwind the resulting array did not sort properly see below:
db.collection.aggregate([
{
{$unwind: '$testOne.scores'},
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"}
}
{$sort:{concatTestOne: 1}},
}
The result was [1,5,8,3,4,5,....,9,0,1]. No sorting
So to get all the tests scores I used reduce to flatten the nested arrays resulting from the grouping stage with no 'unwinding' e.g.:
db.collection.aggregate([
{
{$group:{
_id: {},
concatTestOne: { $push: "$testOne.scores"}
},
{$addFields:{
testOneScores: {$reduce: {
input: "$concatTestOne",
initialValue: [ ],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
}
}
Once again the resulting arrays do not sort. Can anyone tell me what I am doing wrong. The arrays are large (length approx 3500) is it just mongoDB aggregation doesn't handle large arrays ?
Many thanks for any comments I have spent a lot of time trying to sort my arrays and noting works so far
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.