Javascript MongoDB节点MongoDB本机映射/还原
我有一个使用node mongodb native的map/reduce方法。我试图只返回“product_id”上的不同记录。这就是我到目前为止所做的:Javascript MongoDB节点MongoDB本机映射/还原,javascript,node.js,mongodb,database,Javascript,Node.js,Mongodb,Database,我有一个使用node mongodb native的map/reduce方法。我试图只返回“product_id”上的不同记录。这就是我到目前为止所做的: var map = function() { emit("_id", {"_id" : this._id, "product_id" : this.product_id, "name" : this.n
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);
}
});
我的逻辑有些地方似乎不起作用。它仍然会在产品id相同的地方添加重复记录
任何帮助都会很棒-谢谢 事实上,您试图做的一个例子是:
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 :/
}
但请注意,有两种不同的类型:
- 第一次发现
- 最后发现
var finailise = function(key, value){
return value[value.length-1];
}
或者类似的东西,无论如何都应该让你开始
希望有帮助,您的地图对于初学者来说是错误的尝试:
emit(this.product\u id,{“\u id”:this.\u id,“name”:this.name})
跳过reduce,在finalize中从输出的文档中删除除[0]
以外的所有值行,bam您就拥有了唯一的文档。如果您准确地解释了文档的结构以及您希望从map reduce中得到的最终结果,这将非常有用。