MongoDB : write Aggregation result into a new collection
By:Roy.LiuLast updated:2019-08-17
This article shows you 2 ways to export a MongoDB “aggregation” result into another new collection.
1. $out Example
This $out operator is New in version 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. Classic Insert Example
This is a classic way to export the result into a new collection.
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. The toArray() is what you want.
> 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());
Full example to insert the aggregate result into a new collection.
> var result = db.hc_hosting.aggregate( { $group : { _id : "$hosting", total : { $sum : 1 } ); > db.hc_hosting_sum.insert(result.toArray());
References
From:一号门
COMMENTS