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"
}
]
}
]
CodePudding user response:
One option is:
- Keep only documents with a
hockey
game - Set
hockeyData
with the firsthockey
item per each document $sort
and format
db.collection.aggregate([
{$match: {gameDetails: {$elemMatch: {gameName: "hockey"}}}},
{$set: {hockeyData: {
$first: {$filter: {
input: "$gameDetails",
cond: {$eq: ["$$this.gameName", "hockey"]}
}}
}}},
{$sort: {"hockeyData.playDate": -1}},
{$unset: "hockeyData"}
])
See how it works on the playground example
CodePudding user response:
you can either use the $sortArray
or sort outside of the database by adding that condition to your sorting function.
var arr = your array
var result = arr.sort(function (a, b) {
var aDate = new Date(a.gameDetails[0].playDate);
var bDate = new Date(b.gameDetails[0].playDate);
if (
a.gameDetails[0].gameName == "hockey" &&
b.gameDetails[0].gameName == "hockey"
) {
return bDate - aDate;
} else {
return aDate - bDate;
}
})