Get all objects for each tag

127 views Asked by At

I'm new in mongodbs mapreduce and for sure I have not completely understood it for now. And I have a problem, which I try to solve for few days without success.

I have a collection of let's say posts with a tags field. Now I want to mapreduce a new collection of tags. Where every tag have an array of all posts ids that have this one particular tag assigned.

one of my attempts to do this (which doesn't do this right)

m = function() {
    for (var i in this.tags) {
    emit(this.tags[i], {"ids" : [this._id]});
};
}

r = function(key, emits) {
var total = {ids : []}
for (var i in emits) {
    emits[i].ids.forEach(function(id) {
        total.ids.push(id);
    }
} 
return total;
};

I know, that I have to pivot the date some how around, but I just cant get my head wrapped around it.

1

There are 1 answers

0
Jenna On BEST ANSWER

I think you're missing a ")" in your reduce function to close the emits[i].ids.forEach(). Is this what you're trying to do?

r = function (key, values) {
    var total = {ids:[]};
    for (var i in values) {
        values[i].ids.forEach(
            function (id){
                 total.ids.push(id);
            }
        );
    }
    return total;
}

input

{_id:2, tags: ["dog", "Jenna"]}
{_id:1, tags: ["cat", "Jenna"]}

result:

{"results" : [
        {"_id" : "Jenna",
         "value" : {"ids" : [2,1]}
        },
        {"_id" : "cat",
         "value" : {"ids" : [1]}
        },
        {"_id" : "dog",
         "value" : {"ids" : [2]}
        }
    ],
    "timeMillis" : 1,
    "counts" : {
        "input" : 2,
        "emit" : 4,
        "reduce" : 1,
        "output" : 3
    },
    "ok" : 1,
}