10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mongoDB で日毎に集計

Posted at

以下のように日付を表すキーを作って mapReduce することで、ドキュメントの数を日毎に集計できます。

function map() {
  var dateKey = function (d) {
    var yy = d.getFullYear();
    var mm = d.getMonth() + 1;
    var dd = d.getDate();
    if (mm < 10) mm = '0' + mm; 
    if (dd < 10) dd = '0' + dd; 
    
    return yy + '-' + mm + '-' + dd; 
  };  
  emit(dateKey(this.created_at), 1); 
}
function reduce(key, values) {
  return Array.sum(values);
}

var daily_counts = db.logs.mapReduce(map, reduce, { query: {}, out: { inline: 1 } });
daily_counts.results.forEach(function (day) {
  print(day._id + ', ' + day.value);
});

同じような感じで月毎や曜日毎などでも集計できるはずです。

また、ドキュメントの数でなく、売り上げ金額など何らかの数値を集計したい場合は map の最後で以下のようにするといいと思います。

emit(dateKey(this.created_at), this.amount);
10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?