Search code examples
mongodbrestheart

Creating multiple aggregations using RestHeart


I am using RestHeart to make REST calls for MOngoDB aggregation queries.I am trying to create multiple aggregations as a one time activity and then execute them whenever i need them later. Currently I see that only one aggregation gets created at a time. If I create a new one then it gets overwritten.

Is it possible to create multiple aggregations as a one time activity with diferent URI?

This way, I can call URI later and don't have to rewrite the aggregation queries everytime.


Solution

  • RESTHeart allows to define aggregations via the aggrs collection property. See the documentation here https://softinstigate.atlassian.net/wiki/x/AwDw

    aggrs is an array of aggregation definitions, something like:

    aggrs: [ { <aggregation_1> }, { <aggregation_2> }, ... ]
    

    an aggregation definition is:

    {
       "type":"pipeline",
       "uri": <uri>,
           "stages": [
           "<stage_1>",
           "<stage_2>",
           ...
       ]
    }
    

    each aggregation is bound to the uri specified in the definition, under the /db/coll/_aggrs, so:

    GET /db/coll/_aggrs/aggreation1
    GET /db/coll/_aggrs/aggreation2
    

    You say that your aggregation gets overwritten, I suspect that you are updating your collection replacing the aggrs array. Make sure to update the collection properties with all your aggregation definitions in the aggrs array

    So to create a first aggregation using the brilliant httpie cli tool

    http PATCH <ip>/db/coll aggrs:='[ {<aggregation_1>} ]'
    

    To create a second aggregation you can either pass whole the aggrs array:

     http PATCH <ip>/db/coll aggrs:='[ {<aggregation_1>}, {<aggregation_2>} ]'
    

    or add the second one to the aggrs array using the $addToSet update operator

     http PATCH <ip>/db/coll aggrs:='{"$addToSet": {"aggrs": {<aggregation_2>}}}'