Main Tutorials

MongoDB : write Aggregation result into a new collection

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

  1. $out (aggregation)
  2. Aggregation Framework Operators

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments