1

I have a GameStatistics collection and I would like to sort all the players DESC by their points.

All the players are listed in a nested activePlayers array with a game. Each player has a field points (I have put the code and the Schema down below).

It seems that I am missing something, I've already tried with aggregate() but no luck either.

sort = async (req: Request, res: Response, next: NextFunction) => {
  const id = "0021900805";
  const stats = await GameStats.findById(id)
    .sort({ "vTeam.activePlayers.points": -1 })
    .exec();
  return res.status(200).json(stats);
};

The collection looks like this:

[
  {
    "vTeam": {
      "activePlayers": [
        {
          "teamId": "1610612759",
          "firstName": "Lonnie",
          "lastName": "Walker IV",
          "points": "23",
          "assists": "0",
          "rebounds": "4",
          "fgp": "40.0",
          "to": "0",
          "stl": "3",
          "blk": "0"
        },
        {
          "teamId": "1610612759",
          "firstName": "LaMarcus",
          "lastName": "Aldridge",
          "points": "4",
          "assists": "3",
          "rebounds": "14",
          "fgp": "45.0",
          "to": "2",
          "stl": "1",
          "blk": "1"
        }
      ]
    },
    "_id": "0021900805",
    "createdAt": "2020-04-05T15:34:26.457Z",
    "vTeamScore": "114"
  }
]

2 Answers 2

3

You can use mongodb aggregation framework to solve this problem.

Playground

sort = async (req: Request, res: Response, next: NextFunction) => {
  const id = "0021900805";
  const stats = await GameStats.aggregate([
    {
      $match: {
        _id: id, // or mongoose.Types.ObjectId(id)
      },
    },
    {
      $unwind: "$vTeam.activePlayers",
    },
    {
      $sort: {
        "vTeam.activePlayers.points": -1,
      },
    },
    {
      $group: {
        _id: "$_id",
        activePlayers: {
          $push: "$vTeam.activePlayers",
        },
        doc: {
          $first: "$$ROOT",
        },
      },
    },
    {
      $replaceRoot: {
        newRoot: {
          $mergeObjects: [
            "$doc",
            {
              vTeamActivePlayers: "$activePlayers",
            },
          ],
        },
      },
    },
    {
      $addFields: {
        "vTeam.activePlayers": "$vTeamActivePlayers",
      },
    },
    {
      $project: {
        vTeamActivePlayers: 0,
      },
    },
  ]);

  return res.status(200).json(stats);
};
Sign up to request clarification or add additional context in comments.

Comments

0

According to mongoose's docs your solution would be to replace 1 with -1

So: const stats = await GameStats.findById(id).sort({'vTeam.activePlayers.points': -1}).exec();

1 Comment

Yes, I know. The actual array is much bigger. I changed it up to see if would the sort() would sort anything at all (wich it doesn't). But I forgot to change it back

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.