我在 MongoDB 中创建了一个“帖子”集合,其中包含标题、描述、作者、评论:
db.posts.insert({
title:'MongoDB',
description:'MongoDB is a NoSQL DB',
by:'Tom',
comments:[
{user:'ram',
message:'We use MongoDB'
}
]
}
)
同样,我添加了另外两个条目。 现在,我想编写 MapReduce 函数来统计 MongoDB 中不同用户创建的帖子数量。我用过:
db.posts.mapReduce(
function() { emit(this.user_id,1); },
function(key, values) {return Array.sum(values)}, {
out:"post_total"
}
).find()
此输出:
{"id": null , "value": 3}
但是,我想显示的是这样的:
{ "_id" : "tom_id", "value" : 2 }
{ "_id" : "mark_id", "value" : 1 }
或
{ "by" : "tom", "value" : 2 }
{ "by" : "mark", "value" : 1 }
最佳答案
终于解决了。我从 MapReduce function in MongoDB - Grouping document by ID 得到了一些想法
db.posts.mapReduce(
function() { emit(this.by,1); },
function(key, values) {return Array.sum(values)}, {
out:"post_total"
}
).find()
我做错的是,emit(this.user_id,1)。我传递了错误的 key 。
关于mongodb - 编写 MapReduce 函数来统计 MongoDB 中各个用户创建的帖子数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030644/