MongoDB:集計結果を新しいコレクションに書き込む
この記事では、MongoDBの “集約”結果を別の新しいコレクションにエクスポートする2つの方法を示します。
1. $ out例
この `$ out`演算子は、バージョン2.6の新機能です。
1.1簡単なグループ化の例を見直し、結果を新しい変数 “result”に書き込みます。
> var result = db.hc__hosting.aggregate( { $group : { __id : "$hosting", total : { $sum : 1 } } } );
1.2同じ例ですが、
$ out`演算子を使用して結果を新しいコレクション
hc
hosting
stat`にエクスポートします。
> db.hc__hosting.aggregate( { $group : { __id : "$hosting", total : { $sum : 1 } } }, { $out : "hc__hosting__stat" } );
2.古典的な挿入の例
これは、結果を新しいコレクションにエクスポートする古典的な方法です。
2.1結果を “result”変数に代入します。
> var result = db.hc__hosting.aggregate( { $group : { __id : "$hosting", total : { $sum : 1 } } } );
2.1 “result”変数で利用可能なメソッドのリスト。 `toArray()`はあなたが望むものです。
> result.help() Cursor methods .toArray() - iterates through docs and returns an array of the results .forEach( func ) .map( func ) .hasNext() .next() .objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued) .itcount() - iterates through documents and counts them .pretty() - pretty print each document, possibly over multiple lines
2.3次のような結果を挿入します。
> db.hc__hosting__sum.insert(result.toArray());
集計結果を新しいコレクションに挿入する完全な例。
> var result = db.hc__hosting.aggregate( { $group : { __id : "$hosting", total : { $sum : 1 } } } ); > db.hc__hosting__sum.insert(result.toArray());
参考文献
(凝集)]。
http://docs.mongodb.org/master/reference/operator/aggregation/
[Aggregation
フレームワークオペレータ]