Best practices on managing calculated / derived data

I have a product collection. For every product a user can leave a review with a 5-star rating which is stored in a reviews collection.

I’m now trying to get the average rating for every product in my collection. To accomplish this, should I keep an average_rating field on my product and update it every time a new review is created or is there a special way to handle “calculated” fields?

If this is the way to do it, is there a way to use abac to handle this? Since I don’t want users to be able to set the average_rating of a product to just anything.

Hi @jescowuester ,

I guess you can create an index on the 'review0 collection, returning the rating for each document:

CreateIndex(
  {
    name:'ratings',
    source:Collection("<collection_name>"),
    values:[{field:['data','rating']}]
  }
)

and then:

Mean(Match('ratings'))

or

Round(Mean(Match('ratings')),2)

Hope this helps.

Luigi

1 Like