Scenario: I have to aggregate the latest version of balance of all the customers in a particular branch of a bank
Document in mongo that is to be aggregated
{
"_id" : {
"AccountNumber" : "123",
"branchId" : "AXC",
"@objectName" : "AccountBalance"
},
"Versions" : [
{
"value" : NumberDecimal("96562.88"),
"version" : NumberLong(1)
},
{
"value" : NumberDecimal("9612.88"),
"version" : NumberLong(2)
}
]
}
I tried this but returns 0 for the result:
db.getCollection('AccountInfo').aggregate([
{ "$project": { "Versions": { "$slice": [ "$Versions", -1 ] } } },
{ "$match": {
"_id.@objectName" : "AccountBalance",
}},
{ "$group": { "_id": "$_id.branchId", "total": { "$sum": "$Versions.value" } } },
{ "$sort": { "total": -1 } }
])
Any help is appreciated.