试图获得MongoDB字段中每个单词的计数是MapReduce的工作吗?

我collections了一大堆正文post。 例如:

posts = { { id: 0, body: "foo bar baz", otherstuff: {...} }, { id: 1, body: "baz bar oof", otherstuff: {...} }, { id: 2, body: "baz foo oof", otherstuff: {...} } }; 

我想弄清楚如何遍历集合中的每个文档,并对每个文章主体中的每个单词进行计数。

 post_word_frequency = { { foo: 2 }, { bar: 2 }, { baz: 3 }, { oof: 2 }, }; 

我从来没有使用过MapReduce,对于mongo我还是很新鲜的,但是我正在看http://cookbook.mongodb.org/patterns/unique_items_map_reduce/上的文档

 map = function() { words = this.body.split(' '); for (i in words) { emit({ words[i] }, {count: 1}); } }; reduce = function(key, values) { var count = 0; values.forEach(function(v) { count += v['count']; }); return {count: count}; }; db.posts.mapReduce(map, reduce, {out: post_word_frequency}); 

作为一个额外的困难,我在node.js(与节点mongo本地,但愿意切换到如果有一个更简单的方法做减less查询)。

  var db = new Db('mydb', new Server('localhost', 27017, {}), {native_parser:false}); db.open(function(err, db){ db.collection('posts', function(err, col) { db.col.mapReduce(map, reduce, {out: post_word_frequency}); }); }); 

到目前为止,我在节点告诉我ReferenceError: post_word_frequency is not defined (我试图在shell中创build它,但仍然没有帮助)有困难。

那么有没有人用node.js做过mapreduce? 这是用于减less地图的错误吗? 也许另一种方法呢? (也许只是循环和插入另一个集合?)

感谢您的任何反馈和build议! 🙂

编辑 Ryanos下面是正确的(谢谢!)我的基于MongoDB的解决scheme中缺less的一件事是find集合并将其转换为数组。

  db.open(function(err, db){ db.collection('posts', function(err, col) { col.find({}).toArray(function(err, posts){ // this line creates the 'posts' array as needed by the MAPreduce functions. var words= _.flatten(_.map(posts, function(val) { 

这个错误与{out: post_word_frequency}也许你想{out: "post_word_frequency"}但它应该工作没有这个outvariables。

使用underscore可以简单地完成。

 /* [{"word": "foo", "count": 1}, ...] */ var words = _.flatten(_.map(posts, function(val) { return _.map(val.body.split(" "), function(val) { return {"word": val, "count": 1}; }); })); /* { "foo": n, ... } */ var count = _.reduce(words, function(memo, val) { if (_.isNaN(++memo[val.word])) { memo[val.word] = 1; } return memo; }, {}); 

现场示例

_.reduce_.map . _.isNaN_.flatten . _.map_.isNaN . _.flatten