Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF/ELSE in map reduce

Tags:

mongodb

I am trying to make a simple map/reduce function on one of my MongoDB database collections. I get data but it looks wrong. I am unsure about the Map part. Can I use IF/ELSE in this way?

UPDATE

I want to get the amount of authors that ownes the files. In other words how many of the authors own the uploaded files and thus, how many authors has no files.

The objects in the collection looks like this:

{
    "_id": {
        "$id": "4fa8efe33a34a40e52800083d"
    },
    "file": {
        "author": "john",
        "type": "mobile",
        "status": "ready"
    }
}

The map / reduce looks like this:

$map = new MongoCode ("function() {

if (this.file.type != 'mobile' && this.file.status == 'ready') {

 if (!this.file.author) {

  return;

 }

 emit (this.file.author, 1);

}

}");

$reduce = new MongoCode ("function( key , values) {

 var count = 0;

 for (index in values) {

  count += values[index];

 }

 return count;

}");

$this->cimongo->command (array (

 "mapreduce" => "files",  

 "map"       => $map,   

 "reduce"    => $reduce,  

 "out"       => "statistics.photographer_count"

)

);
like image 660
Jonathan Clark Avatar asked May 16 '26 08:05

Jonathan Clark


1 Answers

The map part looks ok to me. I would slightly change the reduce part.

values.forEach(function(v) {
  count += v;
}

You should not use for in loop to iterate an array, it was not meant to do this. It is for enumerating object's properties. Here is more detailed explanation.

Why do you think your data is wrong? What's your source data? What do you get? What do you expect to get?

like image 111
Sergio Tulentsev Avatar answered May 18 '26 01:05

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!