0

I have a mongo document with several fields -

User: { paid_visits: 10, free_visits: 10, totalLength: 120, avgRevenue: 4.4 }

I update the visits and the total length automatically, but in order to compute the avgRevenue, I need to do a computation based on totalLength, paid_visits and free_visits.

Currently I need to get the user, compute the avgRevenue, and then update it.

What I would like to do is to update the avgRevenue every time I update any other field. How can I do that?

Yossale
  • 14,165
  • 22
  • 82
  • 109

1 Answers1

0

MongoDB does not have any server-side support for triggers, but irrespective this requirement seems like something you could best handle in your application model since it is limited to a specific document type.

If you are using a framework/ODM they often support or hooks based on various trigger points in the lifecycle of your request.

For example, the Mongoid ODM for Ruby has a number of useful callbacks that allow you to invoke application logic at appropriate points such as before_save for a document. Your callback could check if any of the dependent fields have changed and only do the avgRevenue recalculation if required.

Stennie
  • 63,885
  • 14
  • 149
  • 175