MongoDB:集計結果を新しいコレクションに書き込みます
この記事では、MongoDBの「集計」結果を別の新しいコレクションにエクスポートする2つの方法を示します。
1. $out Example
この$out演算子は、バージョン2.6の新機能です。
1.1 Review a simple grouping example, it writes the result to a new variable “result”.
> var result = db.hc_hosting.aggregate(
{
$group : {
_id : "$hosting",
total : { $sum : 1 }
}
}
);
1.2 Same example, but use $out operator to export the result into a new collection hc_hosting_stat.
> db.hc_hosting.aggregate(
{
$group : {
_id : "$hosting",
total : { $sum : 1 }
}
},
{
$out : "hc_hosting_stat"
}
);
2. 古典的な挿入の例
これは、結果を新しいコレクションにエクスポートする古典的な方法です。
2.1 Assigns the result to a “result” variable.
> var result = db.hc_hosting.aggregate(
{
$group : {
_id : "$hosting",
total : { $sum : 1 }
}
}
);
2.1 List of the available methods in the “result” variable. 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 Insert the result like the following :
> 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());