Consider the below sample document, which I am trying to get the recent values.
{
"_id" : ObjectId("5ff32c8b6cff64b8582a7c12"),
"Transaction" : [
{
"StatusCode" : "1",
"Amount" : NumberDecimal("300"),
"CreatedDateTime" : ISODate("2021-01-01T10:27:41.746Z")
},
{
"StatusCode" : "2",
"Amount" : NumberDecimal("-750"),
"CreatedDateTime" : ISODate("2021-01-02T10:27:41.746Z")
},
{
"StatusCode" : "1",
"Amount" : NumberDecimal("1500"),
"Date" : ISODate("2021-01-03T10:27:41.746Z")
}
]
}
The Aggregate query that I tried
[{$unwind:
{
path: '$Transaction'
}}, {$group: {
_id: "$Transaction.StatusCode",
Payments : {
$push: '$Transaction'
}
}}, {$group: {
_id: null,
Paid: {
$push: {
$arrayElemAt: [
'$Payments.Amount',
{
$indexOfArray: [
'$Payments',
{
$max: '$Payments.CreatedDateTime'
}
]
}
]
}
}
}}]
Results which I got
{
"_id" : null,
"Paid" : [
NumberDecimal("1500"),
NumberDecimal("-750")
]
}
Can this query be possible to optimize without using unwind or any other way to bring this result?