尝试获取MongoDB字段中每个单词的计数这是MapReduce的工作吗?
我有一个收藏,里面有一堆身体贴子。例如:尝试获取MongoDB字段中每个单词的计数这是MapReduce的工作吗?,mongodb,node.js,mapreduce,Mongodb,Node.js,Mapreduce,我有一个收藏,里面有一堆身体贴子。例如: posts = { { id: 0, body: "foo bar baz", otherstuff: {...} }, { id: 1, body: "baz bar oof", otherstuff: {...} }, { id: 2, body: "baz foo oof", otherstuff: {...} } }; 我想弄清楚如何循环浏览集合中的每个文档,并对每个帖子正文中的每个单词进
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还很熟悉,但我正在查看关于MapReduce的文档
作为一个额外的困难,我在node.js中完成了它(使用node mongo native,不过如果有更简单的方法,我愿意切换到reduce查询)
到目前为止,我很难让该节点告诉我ReferenceError:post\u word\u frequency没有定义(我尝试在shell中创建它,但仍然没有帮助)
有人用node.js做过mapreduce吗?这是map reduce的错误用法吗?也许还有别的办法?(也许只是循环并插入另一个集合?)
感谢您的反馈和建议!:)
编辑下面的Ryanos是正确的(谢谢!)我基于MongoDB的解决方案缺少的一件事是找到集合并将其转换为数组
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\u word\u frequency}
可能需要{out:post\u word\u frequency}
但是如果没有这个out
变量,它应该可以工作
使用它很简单
/*
[{"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;
}, {});
这太棒了!谢谢我下班回家后会核对答案,如果有问题会告诉你。我以前从未见过下划线,可以在node.js中加载吗?@AlexC justnpm install underline
&&&code>var=require(“下划线”)代码>太好了!在你的例子中,它确实有效——我仍在尝试收集mongo位上的所有点,但我相信很快就会出现。谢谢你一吨!:)
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) {
/*
[{"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;
}, {});