Aggregation
Aggregating collections is easiest using the Javascript SDK.
It can be done with the combination of an aggregation function like count()
and, optionally, groupBy()
which are discussed in the Configuring the Javascript SDK (JS SDK) page.
However when aggregating a collections property directly, aggregation requests are made by adding the agg query
variable; agg[func]=aggFunction
, where aggFunction
is the name of the aggregate function you wish to apply.
This is discussed in the Supported aggregate functions section below.
Next in the query string you must specify agg[prop]=document.myProperty
where myProperty
is the name of the property whose values in the collection to which the aggregate function will be applied.
The final optional query string parameter you may specify is agg[group]=document.myProperty[,document.myProperty…]
where myProperty
are the names of the properties by which to group the aggregation.
The unique values of the properties listed form groups to which the aggregate function is applied. The unique values and then the result of aggregation will make up the result.
Array and source properties are not available as grouping properties. |
Aggregation of documents in a collection can be combined with filter queries to further limit the documents values being aggregated.
The simplest example to aggregate a collection is to count a collection and apply the system documentid
property to the count function.
An example of this using CURL is shown below:
curl \
-X GET \
-H "Content-Type: application/json" \
--silent \
-fS https://my-data-service.datastore.squiz.cloud/my-first-collection?agg[func]=count&agg[prop]=document.$id
The resulting aggregation response:
{
"aggregate": 5
}
If you group this result by the imagined student type property where the type value may be local or international the CURL request would look like:
curl \
-X GET \
-H "Content-Type: application/json" \
--silent \
-fS https://my-data-service.datastore.squiz.cloud/my-first-collection?agg[func]=count&agg[prop]=document.$id&agg[group]=document.type
The resulting aggregation response:
{
"aggregate": {
“International”: 2
“local”: 3
}
}