node.js - Get Sum of Values in MongoDB -


i have array , each list item in array object has value key. add of values total. want on end rather front end. have tried aggregate method, haven't had luck returns empty array. here array:

"budgets" : [     {         "name" : "check",         "value" : "1000",         "expense" : "false",         "uniqueid" : 0.9880268634296954     },     {         "name" : "car",         "value" : "500",         "expense" : "true",         "uniqueid" : 0.1904486275743693     },     {         "name" : "car2",         "value" : "500",         "expense" : "false",         "uniqueid" : 0.23043920518830419     },     {         "name" : "car23",         "value" : "500",         "expense" : "false",         "uniqueid" : 0.014449386158958077     },     {         "name" : "car235",         "value" : "500",         "expense" : "false",         "uniqueid" : 0.831609656335786     } ], 

what want total of values have "expense" : "true" , separate total of "expense" : "false" how this? said have tried aggregate method, must doing wrong.

if new using aggregation framework commands might not yet aware of $cond operator. can use in order totals separated:

db.collection.aggregate([      // unwind array de-normalize items     { "$unwind": "$budgets" },      // group totals conditions     { "$group": {         "_id": "$_id",         "expense": { "$sum": {              "$cond": [                 "$budgets.expense",                 "$budgets.value",                 0             ]         }},         "nonexpense": { "$sum": {              "$cond": [                 "$budgets.expense",                 0,                 "$budgets.value"             ]         }}      }}  ]) 

so evaluate true/false condition of expense first argument, , when condition true second argument of $cond chosen , passed on $sum. if condition evaluates false second argument chosen.

but looking @ data appear have problem:

    {         "name" : "check",         "value" : "1000",         "expense" : "false",         "uniqueid" : 0.9880268634296954     }, 

noting here of fields, , notably expense , value items, strings. problem while around evaluating true/false values doing string comparisons rather direct boolean, cannot co-erce string number can passed $sum.

so firstly need fix data, unless not in form have represented. when meets correct form, can aggregation.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -