Skip to content
Jon Clausen edited this page Jan 1, 2016 · 1 revision

Aggregation

Aggregation of your results allows you to filter, calculate new values and group them in a result set.

CBMongoDB has suppoort for the aggregation methods of $group, $match, $projection and $sort in the Collection object's aggregate([criteria],group,projection,sort) method.

Here's an example, using our people collection. In this case we want to return a query that returns the number of people, by Zip Code, in Grand Rapids, Michigan. Our aggregation query would be assembled like so:

//We'll need our db collection object for this operation
var Collection = people.getDBInstance();

//Match Grand Rapids, Michigan
var agMatch={"city":"Grand Rapids","state":"Michigan"};

//Create the group parameters for our results.  Note the self-referential use of "$" before postalcode
var agGroup={"_id":"$postalcode","count":{"$sum":1}};
//Sort those records ascending
var agSort={"_id":1};
var aggregation = Collection.aggregate(
	criteria=agMatch,
	group=agGroup,
	sort=agSort
);

This would return a result in which the result array (represented as JSON below), would look like:

[
	{
		"_id":49503,
		"count":25
	},
	{
		"_id":49506,
		"count":15
	},
	{
		"_id":49512,
		"count":1
	}
]

For more information on Aggregation functionality see the API docs for the module and view Mongo's Documentation.