MongoDB: écrire le résultat d'agrégation dans une nouvelle collection
Cet article vous montre 2 façons d'exporter un résultat d'agrégation MongoDB dans une autre nouvelle collection.
1. $out Example
Cet opérateur$out
est nouveau dans la 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. Exemple d'insertion classique
C'est une façon classique d'exporter le résultat dans une nouvelle 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. LetoArray()
est ce que vous voulez.
> 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());
Exemple complet pour insérer le résultat agrégé dans une nouvelle collection.
> var result = db.hc_hosting.aggregate( { $group : { _id : "$hosting", total : { $sum : 1 } } } ); > db.hc_hosting_sum.insert(result.toArray());