R
R
Roman2017-06-20 14:04:22
MongoDB
Roman, 2017-06-20 14:04:22

What is the correct way to write mapReduce for MongoDB?

Good afternoon. Please help me figure it out. There is a collection of bankGuarantee
I write mapReduce like this:

var map = function(){
    var key = {
        regNum: this.regNumber,
        bank_name: this.bank.shortName,
        bank_inn: this.bank.INN,
        year: this.guarantee.guaranteeDate.getFullYear(),   //Дата выдачи БГ.Год
        month: this.guarantee.guaranteeDate.getMonth(),     //Дата выдачи БГ.Месяц
        category: getCategory(this.guarantee.guaranteeAmount)
    };
    
    emit(key, {count:1, bg_amount: this.guarantee.guaranteeAmount /*,Сумма контракта*/});
}

var reduce = function(key, values){
    var bg_count = 0;
    var bg_amount = 0;
    
  values.forEach(function(value) {
    bg_count += value['count'];
    bg_amount += value['bg_amount'];
  });
  
  return {count: bg_count, amount: bg_amount};
}

db.bankGuarantee.mapReduce(map, reduce, {out: 'bg_stats'});

I can’t understand some points:
1. the key has a regNum field: this.regNumber, but I don’t need it in the key, I need the count for all keys to be calculated on average, like avg in sql, if there is a document with the same topic in the key but the code occurs n times, then the count for these documents should be equal to one, how to write it correctly?
2. year: this.guarantee.guaranteeDate.getFullYear() The guaranteeDate field may either be missing or named differently in some documents, what is the best way to handle this situation?
3. Also, the year is returned as a Double as a result, how to make it an integer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-06-21
@losaped

if a document with the same code occurs n times in the key, then the count for these documents should be equal to one
. What do you mean, Roman ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question