mongodb - Finding the Sum of a field (if it exists

2019-07-10 08:42发布

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 } });

1条回答
The star\"
2楼-- · 2019-07-10 09:08

I was finally able to figure it out and get it working. I have shared my code below.

var map = function(){
    if(this.fields.rating){
        emit(this.fields.rating.parent,this.fields.rating.weight);
    }
}

var reduce = function (k, vals) {
    var sum = 0;
    var count = 0;
    for (var i in vals) {
        sum += vals[i];
    count++;
    }
    var avg = (sum/count);
    return avg;
}

var res = db.myCollection.mapReduce(map, reduce, {out:"myoutput"});
查看更多
登录 后发表回答