How to sort embedded array in-place with $sortArray in Mongoose

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

I misstated the version. We’re on v5.0.8 which doesn’t have $sortArray. It’s a managed service so upgrade is beyond our control.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.