Aggregate sum of nested MongoDB array elements in a collection

تعرفه تبلیغات در سایت

آخرین مطالب

امکانات وب

Vote count: 0

Scenario: I have to aggregate the latest version of balance of all the customers in 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 is not working-

db.getCollection('AccountInfo').aggregate

([
   { $project: {Versions: { $slice: [ "$Versions", -1 ] } } }
     ,{ $match: {    
        "_id.@objectName" : "AccountNumber",
     } },
                     { $group: {_id: "$_id.objectName", total: { $sum: "$Versions.value" } } },
                     { $sort: { total: -1 } }   ]   );
asked 47 secs ago
SuryaVal

نویسنده : استخدام کار بازدید : 9 تاريخ : چهارشنبه 19 ارديبهشت 1397 ساعت: 9:11

فهرست وبلاگ