使用map reduce计算集合中的文档总数?

时间:2013-04-26 13:53:16

标签: mongodb mongomapper

我有这样的“统计”集合:

{ "_id" : ObjectId("4d2407265ff08824e3000001"), "request_uri" : {"netloc":"localhost/8080", "path":"vi/sitelicense"}, "api_key" : "apikey", "request_method" : "POST" }
    { "_id" : ObjectId("4d2551b4ae9fa739640df821"), "request_uri" : {"netloc":"localhost/8080", "path":"vi/sitelicense"}, "api_key" : "apikey", "request_method" : "GET" }
    { "_id" : ObjectId("4d255b115ff08821c2000001"), "request_uri" : {"netloc":"localhost/8080", "path":"vi/sitelicense"}, "api_key" : "apikey", "request_method" : "POST" }
    { "_id" : ObjectId("4d25e8d55ff08814f8000001"), "request_uri" : {"netloc":"localhost/8080", "path":"vi/sitelicense"}, "api_key" : "apikey", "request_method" : "PUT" }
    { "_id" : ObjectId("4d2407265ff08824e3700001"), "request_uri" : {"netloc":"localhost/8080", "path":"vi/sitelicense"}, "api_key" : "apikey", "request_method" : "POST" }

如何使用map reduce操作找到“statistics”集合中的文档总数? 这是我的地图缩小操作:

map_number_api_calls = function() { 
  emit(this._id, 1);
}
reduce_number_api_call = function(k, v) {
  var i, sum = 0;
  for (i in v) {
    sum += v[i];
  }
  return sum;
}

但是上面的map-reduce操作并没有返回文件总数。我需要收集文件的总数,实际上是5.任何一个例子?

1 个答案:

答案 0 :(得分:4)

你的map / reduce不起作用的原因是你从地图发出的一对值必须包括两件事:

1. Key over which you want to aggregate values
2. Value

您的密钥应该是常量 - 即您希望聚合整个集合,因此您需要将所有发出的值映射到相同的密钥。

emit(this._id, 1)替换为emit(null, 1),它会起作用(它不一定是null可能是1或“”集合“字符串文字或其他任何内容这是不变的。)

除非您这样做是为了学习map / reduce,否则我建议您使用db.collection.count()来获取集合中的项目数。

相关问题