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!
emit(this.product_id, {"_id" : this._id, "name" : this.name });[0]of thevaluesrows from the outputted document and bam you have your unique document.