最近在学习Mongodb,作为入门,选择了《Mongodb权威指南》这本书来进行参考学习。目前看到了MapReduce,由于我用的版本比较新,发现了和书上有些不同的地方。
应用场景:
使用MapReduce找出一个集合中所有的键的个数,mongo shell代码如下:
定义map function:
- map = function () {
- for (var key in this) {
- emit(key, {count:1});
- }
- }
定义reduce function:
- reduce = function (key, emits) {
- total = 0;
- for (var i in emits) {
- total += emits[i].count;
- }
- return {count:total};
- }
执行MapReduce操作:
- mr = db.runCommand({"mapreduce":"users","map":map,"reduce":reduce})
以上都是书上的代码,但是执行后没有正常返回,而是返回了如下结果:
- {
- "assertion" : "'out' has to be a string or an object",
- "assertionCode" : 13606,
- "errmsg" : "db assertion failure",
- "ok" : 0
- }
网上百度了下才知道原来1.8以上的版本需要指定out的输出
修改了执行MapReduce命令后执行正常,命令如下:
- mr = db.runCommand({"mapreduce":"users","map":map,"reduce":reduce,"out":{inline:1}})
也可以使用如下命令方式:
- db.users.mapReduce(map,reduce,{out:{inline:1}})
执行后返回结果如下:
- {
- "results" : [
- {
- "_id" : "_id",
- "value" : {
- "count" : 3
- }
- },
- {
- "_id" : "age",
- "value" : {
- "count" : 1
- }
- },
- {
- "_id" : "email",
- "value" : {
- "count" : 1
- }
- },
- {
- "_id" : "emails",
- "value" : {
- "count" : 1
- }
- },
- {
- "_id" : "favorite book",
- "value" : {
- "count" : 1
- }
- },
- {
- "_id" : "hobby",
- "value" : {
- "count" : 1
- }
- },
- {
- "_id" : "name",
- "value" : {
- "count" : 3
- }
- },
- {
- "_id" : "score",
- "value" : {
- "count" : 2
- }
- }
- ],
- "timeMillis" : 311,
- "counts" : {
- "input" : 3,
- "emit" : 13,
- "reduce" : 3,
- "output" : 8
- },
- "ok" : 1
- }