Based on your suggestion I have modified my aggregation result a little bit and this is what I have used :
db.collection.aggregate({
"$unwind": "$flight_records",
},
{
"$group": {
_id: {
$year: {
$toDate: "$flight_records.date_of_journey"
}
},
recordsForYear: {
$push: "$flight_records"
}
}
})
And the result I am getting is this, and I think this should suffice. Is there a more efficient way to do this ? Would love to learn more about this.
[
{
"_id": 2021,
"recordsForYear": [
{
"date_of_journey": "2021-11-18",
"destination": "DTW",
"origin": "DCA",
"real": {
"arr": 1.668740944e+09,
"dep": 1.668736446e+09
},
"scheduled": {
"arr": 1.66874124e+09,
"dep": 1.66873524e+09
},
"status": "Landed 22:09"
},
{
"date_of_journey": "2021-11-16",
"destination": "DCA",
"origin": "DTW",
"real": {
"arr": 1.668644421e+09,
"dep": 1.668640813e+09
},
"scheduled": {
"arr": 1.66864524e+09,
"dep": 1.6686396e+09
},
"status": "Landed 19:20"
},
{
"date_of_journey": "2021-11-14",
"destination": "DCA",
"origin": "DTW",
"real": {
"arr": 1.668471887e+09,
"dep": 1.66846811e+09
},
"scheduled": {
"arr": 1.66847244e+09,
"dep": 1.6684668e+09
},
"status": "Landed 19:24"
}
]
},
{
"_id": 2023,
"recordsForYear": [
{
"date_of_journey": "2023-11-17",
"destination": "DTW",
"origin": "DCA",
"real": {
"arr": 1.668653594e+09,
"dep": 1.668649558e+09
},
"scheduled": {
"arr": 1.66865484e+09,
"dep": 1.66864884e+09
},
"status": "Landed 21:53"
},
{
"date_of_journey": "2023-11-15",
"destination": "DCA",
"origin": "DTW",
"real": {
"arr": 1.668557859e+09,
"dep": 1.668553656e+09
},
"scheduled": {
"arr": 1.66855884e+09,
"dep": 1.6685532e+09
},
"status": "Landed 19:17"
},
{
"date_of_journey": "2023-11-14",
"destination": "DTW",
"origin": "DCA",
"real": {
"arr": 1.668395275e+09,
"dep": 1.668391115e+09
},
"scheduled": {
"arr": 1.66839564e+09,
"dep": 1.66838964e+09
},
"status": "Landed 22:07"
}
]
},
{
"_id": 2022,
"recordsForYear": [
{
"date_of_journey": "2022-11-17",
"destination": "DCA",
"origin": "DTW",
"real": {
"arr": 1.668730907e+09,
"dep": 1.668727074e+09
},
"scheduled": {
"arr": 1.66873164e+09,
"dep": 1.668726e+09
},
"status": "Landed 19:21"
},
{
"date_of_journey": "2022-11-16",
"destination": "DTW",
"origin": "DCA",
"real": {
"arr": 1.668568424e+09,
"dep": 1.668564614e+09
},
"scheduled": {
"arr": 1.66856844e+09,
"dep": 1.66856244e+09
},
"status": "Landed 22:13"
},
{
"date_of_journey": "2022-11-15",
"destination": "DTW",
"origin": "DCA",
"real": {
"arr": 1.668481169e+09,
"dep": 1.668477413e+09
},
"scheduled": {
"arr": 1.66848204e+09,
"dep": 1.66847604e+09
},
"status": "Landed 21:59"
}
]
}
]