This is a question about the best way to add up a series of data in an array where I have to match another element. I\'m trying to use the 2.2 Aggregation framework and it\'
You can use the aggregation framework to get sales and profit and any other value you may be storing in your key/value pair representation.
For your example data:
var pipeline = [
{
"$unwind" : "$finance"
},
{
"$group" : {
"_id" : "$finance.k",
"numberOf" : {
"$sum" : 1
},
"total" : {
"$sum" : "$finance.v.v"
}
}
}
]
R = db.tb.aggregate( pipeline );
printjson(R);
{
"result" : [
{
"_id" : "profit",
"numberOf" : 2,
"total" : 246246
},
{
"_id" : "sales",
"numberOf" : 2,
"total" : 468000
}
],
"ok" : 1
}
If you have additional k/v pairs then you can add a match which only passes through k values in ["sales","profit"].