0

私はそのような「統計」コレクションを持っています:

{ "_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_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 であるコレクション ドキュメントの総数が必要です。例はありますか?

4

1 に答える 1

4

map/reduce が機能しない理由は、マップから出力する値のペアに次の 2 つが含まれている必要があるためです。

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()、コレクション内のアイテムの数を取得するために使用することをお勧めします。

于 2013-04-26T15:01:26.837 に答える