0

我有一个使用 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 相同的重复记录。

任何帮助都会很棒-谢谢!

4

1 回答 1

2

事实上,你试图做的一个例子:

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 :/
}

但是请注意,有两种不同的类型:

  • 首先找到
  • 最后发现

没有标准的区分方法,每个数据库都有自己的方法,它甚至在 SQL 数据库中都不是标准的,所以你要知道你想要区分的方式。上面的第一个发现是不同的。您可以进行最后一次查找,例如:

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

或类似的东西,无论如何应该让你开始。

希望能帮助到你,

于 2012-08-13T20:39:44.100 回答