【发布时间】:2012-08-13 19:11:27
【问题描述】:
我有一个使用 node-mongodb-native 的 map/reduce 方法。我试图只返回“product_id”上的不同记录。这是我目前所拥有的:
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);
}
});
我的逻辑似乎不起作用。它仍然会添加 product_id 相同的重复记录。
任何帮助都会很棒 - 谢谢!
【问题讨论】:
-
你的地图是错误的初学者尝试:
emit(this.product_id, {"_id" : this._id, "name" : this.name }); -
跳过 reduce 并在 finalize 中从输出的文档中删除除
[0]之外的所有values行,然后您就拥有了自己的独特文档。 -
如果您能准确解释文档的结构以及您希望从 map reduce 中得到的最终结果,将会很有帮助。
标签: javascript node.js mongodb database