I want to get Descending order data by date on playDate Attribute, but descending condition is apply on gameName : hockey object
Data
[
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2014-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2022-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2020-05-05T00:00:00.000Z"
},
{
"gameName": "cricket",
"playDate": "2013-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2013-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2009-05-05T00:00:00.000Z"
},
{
"gameName": "hockey",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
}
]
From above data we have to output gave records gameName:hockey which is present in gameDetail Array ,in descending order by playDate attribute of gameName:hockey object
Output is:
[
{
"gameDetails": [
{
"gameName": "cricket",
"playDate": "2009-05-05T00:00:00.000Z"
},
{
"gameName": "hockey",
"playDate": "2021-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2020-05-05T00:00:00.000Z"
},
{
"gameName": "cricket",
"playDate": "2013-06-05T00:00:00.000Z"
}
]
},
{
"gameDetails": [
{
"gameName": "hockey",
"playDate": "2014-05-05T00:00:00.000Z"
},
{
"gameName": "football",
"playDate": "2022-06-05T00:00:00.000Z"
}
]
}
]
2
Answers
you can either use the
$sortArray
or sort outside of the database by adding that condition to your sorting function.One option is:
hockey
gamehockeyData
with the firsthockey
item per each document$sort
and formatSee how it works on the playground example