MongoDB node-mongodb-native map / reduce

I have a map / reduce method using node-mongodb-native. I am trying to return only single entries in '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 is not working with my logic. It still adds duplicate entries where product_id are the same.

Any help would be awesome - thanks!

0
source share
1 answer

In fact, an example of what you are 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 :/ } 

However, note that there are two types of different ones:

  • First find
  • Last find

There is no standard way for different ones, and each database has its own methods, it is not even standard for SQL databases, so you need to know which way you want to distinguish. The above first detects the difference. You can make the latest discovery great, like:

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

Or something like that, you must have started anyway.

Hope this helps,

+2
source

All Articles