【问题标题】:MongoDB node-mongodb-native map/reduceMongoDB node-mongodb-native map/reduce
【发布时间】: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


【解决方案1】:

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

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]; 
}

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

希望对你有帮助,

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多