dzm
dzm

Reputation: 23574

MongoDB node-mongodb-native map/reduce

I have a map/reduce method using node-mongodb-native. I'm trying to only return distinct records on 'product_id'. This is what I have so far:

        var map = function() {
            emit("_id", {"_id" : this._id, 
                         "product_id" : this.product_id,
                         "name" : this.name 
                         });
        }

        var reduce = function(key, values) {

            var items  = [];
            var exists;

            values.forEach(function(value) {

                if(items.length > 0) {

                    items.forEach(function(item_val, key) {
                        if(item_val.product_id == value.product_id) {
                            exists = true;
                        }
                    });

                    if(!exists) {
                        items.push(value);
                    }

                    exists = false;

                } else {

                    items.push(value);
                }
            }); 

            return {"items" : items};
        }

        this.collection.mapReduce(map, reduce, {out : {inline: 1}, limit: 4}, function(err, results) {
            if (err) {
                console.log(err);
            } else {
                console.log(results[0].value.items);
            }
        });

Something with my logic doesn't seem to work. It still adds duplicate records where product_id's are the same.

Any help would be awesome - thank you!

Upvotes: 0

Views: 1641

Answers (1)

Sammaye
Sammaye

Reputation: 43884

In fact, an example of what your trying to do:

var map = function() {
    emit(this.product_id, {"_id" : this._id, "name" : this.name });
}

var finailise = function(key, value){
    return value[0]; // This might need tweaking, ain't done MRs in a while :/
}

Do note however there are two types of distinct:

  • First find
  • Last find

There is no standard way to distinct and each DB has it's own methods, it isn't even standard across SQL databases so it is upto you to know which way you want to distinct. The one above does a first find distinct. You can do a last find distinct like:

var finailise = function(key, value){
    return value[value.length-1]; 
}

Or something similar, should get you started anyway.

Hope it helps,

Upvotes: 2

Related Questions