naga headhunter
naga headhunter

Reputation: 216

Emit with key as zero in map reduce in mongodb

Giving the value of the key as 0 in the emit functions and after reduce it correctly gives the total of a column in the collection as intended. Now my question is I don't understand how this is working.

I have my emit like this;

function(){ emit(0, this.total); }

Could somebody please explain to me the working in this? Thank you in advance.

Upvotes: 0

Views: 255

Answers (2)

Sammaye
Sammaye

Reputation: 43884

To compliment the other answer with some internals, when you emit your single and only key the resulting document from the emit will look something like:

{_id:0,value:[5,6,7,8,9]}

With the array representing the combination of all the emits.

Emits grouped upon the key when you emit so this means there will only be one document with the content of that document being all the total fields in the collection.

So when the reduce comes along and you add all of these numbers together it will correctly sum up the total for all total fields in the collection.

Upvotes: 1

Artem Mezhenin
Artem Mezhenin

Reputation: 5757

MapReduce is a tricky thing. You need to change your mindset to understand it. In your particular case, you told mongo that don't care about grouping options. When you emit like this, all your this.total's will be sent to one batch with identifier 0 and aggregated all-together at reduce step. This also means that this cases are identical:

function(){ emit(0, this.total); }
function(){ emit(1, this.total); }
function(){ emit('asdf', this.total); }
function(){ emit(null, this.total); }

They will lead to save result, even batch name is different.

Upvotes: 2

Related Questions