Search code examples
javascriptdatabasemongodbmongoose

Sorting from a nested array MongoDB


I'm using mongoose to work with my data. So far I've got this here

    const personal = await culvertSchema.aggregate([
      { $match: { "characters.name": selectedCharacter } },
      { $unwind: "$characters" },
      { $sort: { "characters.scores.score": -1 } },
      { $limit: 1 },
    ]);

but it does not seem to work in sorting the 'scores'. Or maybe I'm not even accessing them correctly. I'm not sure. How would I be able to sort the scores of the given character name?

Here's my structure:

{
  "_id": "336277029060345856",
  "characters": [
    {
      "name": "druu",
      "scores": [
        {
          "date": "09/03/23",
          "score": 41
        },
        {
          "date": "09/03/23",
          "score": 12
        },
        {
          "date": "09/03/23",
          "score": 52
        },
        {
          "date": "09/03/23",
          "score": 100
        }
      ]
    },
    {
      "name": "druuwu",
      "scores": []
    }
  ]
}

Thanks!


Solution

  • Perform a $sortArray after your current $unwind

    db.collection.aggregate([
      {
        "$unwind": "$characters"
      },
      {
        "$match": {
          "characters.name": "druu"
        }
      },
      {
        "$set": {
          "characters.scores": {
            "$sortArray": {
              "input": "$characters.scores",
              "sortBy": {
                "score": -1
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground