0

I have "statistic" collection like that:

{ "_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" }

How can i find the total number of documents in my "statistics" collection using map reduce operation? Here is my map reduce operation:

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;
}

But the above map-reduce operation is not returning total number of documents. I need total number of collection documents which is actually 5. Any example?

4

1 回答 1

4

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

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

您的键应该是一个常数 - 即您想要聚合整个集合,因此您需要将所有发出的值映射到同一个键。

替换emit(this._id, 1)emit(null, 1)它会起作用(它不一定是null它可以是1或`“collection”字符串文字或任何其他不变的东西)。

除非您将此作为学习 map/reduce 的练习,否则我建议您使用db.collection.count()它来获取集合中的项目数。

于 2013-04-26T15:01:26.837 回答