MongoDB/Mongoose:无法使用最简单的MapReduce

Raf*_*nte 0 grouping mapreduce mongoose mongodb

大家好我想做的就是获取每个不同departmentType的计数:

fnMap = function() { 
  emit(this.departments.departmentType, {typeCount:1} ); 
} 

fnReduce = function(key, values) { 
  var result = {typeCount: 0}; 
  values.forEach(function(value) {
    result.typeCount += value.brandCount;
  });

  return result;             
};


var command = {
mapreduce : "clients", 
query     : {"departments.departmentType": {$exists: true}},
map       : fnMap.toString(), 
reduce    : fnReduce.toString(),    
    //sort: {"departments.departmentType":1}, 
    out: {inline: 1}   
};

mongoose.connection.db.executeDbCommand(command, function(err, dbres) {

    }); 
Run Code Online (Sandbox Code Playgroud)

执行命令时,dbres.documents [0] .results只包含1个具有departmentTypes总数的项目,而不是包含每个departmentType及其计数的几个项目.

有什么想法我做错了什么?

此外,当我取消注释SORT行时,我收到错误"db assertion failure:无法创建游标...",我相信字段名称是正确写入的.

Gia*_* P. 5

Mongoose v3现在有一个Model.mapreduce()功能(参见doc).

显示的完整示例是:

var o = {};
o.map = function () { emit(this.name, 1) }
o.reduce = function (k, vals) { return vals.length }
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;
User.mapReduce(o, function (err, model, stats) {
  console.log('map reduce took %d ms', stats.processtime)
  model.find().where('value').gt(10).exec(function (err, docs) {
    console.log(docs);
  });
})
Run Code Online (Sandbox Code Playgroud)

我认为计数的问题是因为在你的fnReduce()函数中你是结果而不是在数组中显示结果.