I’m trying to use $sortArray
to sort a collection by a field (‘bandName’), and within each document, sort the embedded array ‘tours’ by date.
In the official example (linked above) sortArray is used in the projection stage. In my case I want keep the shape of the document.
[
{
bandName: "The Beatles",
tours: [
{
date: "2022-09-10"
location: "San Francisco"
},
{
date: "2022-09-15"
location: "Seatle"
}
]
},
...
Code
const rs = await this.bands
.aggregate([
filter,
{
$set: {
tours: {
$sortArray: {
input: '$tours',
sortBy: { 'date': -1 }
}
}
}
},
{
$sort: {
bandName: 1
}
}
]
Error: MongoServerError: Invalid $set :: caused by :: Unrecognized expression '$sortArray
Mongo server version: 6
Mongoose: 6.4.7
Node: 16.4