UPDATED ANSWER
First, to make sure I could test this, I created a collection with the fruit information in it and inserted your example data:
db.fruitmarket.insert(
[
{ marketname : "LA", fruit : { apples : 2, grapes : 3 , pears : 4, oranges : 5} },
{ marketname : "CHI", fruit : { apples : 3, grapes : 5 , pears : 4, oranges : 7} },
{ marketname : "NY", fruit : { apples : 4, grapes : 7 , pears : 6, oranges : 8} }
]
)
map function that emits all the properties of the fruit
key for each document:
function() {
for (var key in this.fruit) {
emit(key, this.fruit[key]);
}
}
reduce function that sums up all of the fruit
values:
function(key, values) {
return Array.sum(values);
}
Finally, I ran the map-reduce:
db.loadServerScripts();
db.fruitmarket.mapReduce(mapSubProperties, reduceSubProperties, { out: "fruits"})
And I got the result you were looking for:
/* 0 */
{
"_id" : "apples",
"value" : 9
}
/* 1 */
{
"_id" : "grapes",
"value" : 15
}
/* 2 */
{
"_id" : "oranges",
"value" : 20
}
/* 3 */
{
"_id" : "pears",
"value" : 14
}