Reputation: 31
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"
}
]
Upvotes: 1
Views: 282
Reputation: 17858
You can use mongodb aggregation framework to solve this problem.
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);
};
Upvotes: 3
Reputation: 5174
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();
Upvotes: 0