MapReduce、MongoDB和节点MongoDB本机
我使用节点mongodb本机库在mongodb上运行MapReduce(从node.js) 这是我的密码:MapReduce、MongoDB和节点MongoDB本机,mongodb,node-mongodb-native,Mongodb,Node Mongodb Native,我使用节点mongodb本机库在mongodb上运行MapReduce(从node.js) 这是我的密码: var map = function() { emit(this._id, {'count': this.count}); }; var reduce = function(key, values) { return {'testing':1}; }; collection.mapReduce( map, reduce,
var map = function() {
emit(this._id, {'count': this.count});
};
var reduce = function(key, values) {
return {'testing':1};
};
collection.mapReduce(
map,
reduce,
{
query:{ '_id': /s.*/g },
sort: {'count': -1},
limit: 10,
jsMode: true,
verbose: false,
out: { inline: 1 }
},
function(err, results) {
logger.log(results);
}
);
两个问题:
1) 基本上,我的reduce函数被忽略了。无论我在其中输入了什么,输出都只是map函数的结果(在本例中没有“测试”)。有什么想法吗
2) 除非在用于排序的字段(在本例中为count字段)上定义了索引,否则会出现错误。我知道这是意料之中的。这似乎效率低下,因为正确的索引肯定是(_id,count)而不是(count),因为理论上应该首先使用_id(用于查询),然后才应该对适用的结果应用排序。我是不是遗漏了什么?MongoDB效率低吗?这是虫子吗
谢谢!:) 从不调用reduce函数的原因是您为每个键发出一个值,因此没有理由实际执行reduce函数。下面是一个如何触发reduce函数的示例
collection.insert([{group: 1, price:41}, {group: 1, price:22}, {group: 2, price:12}], {w:1}, function(err, r) {
// String functions
var map = function() {
emit(this.group, this.price);
};
var reduce = function(key, values) {
return Array.sum(values);
};
collection.mapReduce(
map,
reduce,
{
query:{},
// sort: {'count': -1},
// limit: 10,
// jsMode: true,
// verbose: false,
out: { inline: 1 }
},
function(err, results) {
console.log("----------- 0")
console.dir(err)
console.dir(results)
// logger.log(results);
}
);
请注意,我们是通过“group”键发射的,这意味着有n>=0个条目由“group”键分组。由于您正在发射_id,每个键都是唯一的,因此不需要reduce函数
您是如何执行映射/还原的?您可以粘贴该命令吗?以上是我在node.js中使用node mongodb native(10gen支持的官方客户端代码)的完整代码。节点mongodb native在调用集合的mapReduce时为您运行该命令。库中的代码以“Collection.prototype.mapReduce=“at:我确实在回调中得到了结果,只是它看起来好像reduce函数被忽略了……所以您不会像调用
db.inline.find()
那样调用它,您只需对集合调用mapReduce
?是的。库基于它创建并执行DB命令。库代码位于我前面评论中的链接处。