I have the following mongodb structure
{
"_id": ObjectId("507c80a143188f9610000003"),
"date": ISODate("2012-10-15T21: 31: 13.0Z"),
"uid": NumberInt(35920),
"comp": NumberInt(770),
"fields": {
"rating": {
"parent": "rating",
"weight": NumberInt(2),
"rel_weight": 0.11,
},
"capacity": {
"parent": "capacity",
"weight": NumberInt(4),
"rel_weight": 0.89,
},
}
}
The "fields" attribute has 2 fields "rating" and "capacity" in it. But, each entry might have a different set of fields. eg. dimension, price etc.
I would like to find all entries that have "rating" under "fields" and get a sum of "weight" attribute of all such entries.
I am a newbie to mongodb and I tried using the mapReduce function, but with no avail.
Given below is the code I used. Kindly let me know where I went wrong or if there is a better solution instead of this code.
function map(){
emit(this._id,{weight:this.fields.rating.weight});
}
function reduce(key,value){
var sum = 0;
for ( var i=0; i<value.length; i++ ) {
sum += value[i].amount;
}
return sum;
}
res = db.collection_name.mapReduce(map, reduce, { query: {"fields.rating" : { $exists: true } });