2

In the Mongo docs on materialized views i saw this example:

updateMonthlySales = function(startDate) {
   db.bakesales.aggregate( [
      { $match: { date: { $gte: startDate } } },
      { $group: { _id: { $dateToString: { format: "%Y-%m", date: "$date" } }, sales_quantity: { $sum: "$quantity"}, sales_amount: { $sum: "$amount" } } },
      { $merge: { into: "monthlybakesales", whenMatched: "replace" } }
   ] );
};

I wanted to understand

  • where do I write this function,
  • and how I can invoke it

It would be extra amazing if anyone has a solution from a Play-Framework/Reactive Mongo pov. Reactive-Mongo's way of writing aggregation is quite difficult imo, and I wanted to find a different way to trigger an aggregation, which. updates a view, which will be read by my application.

Any help would be very much appreciated :)

Somjit
  • 2,503
  • 5
  • 33
  • 60
  • Have a look at the [documentation](http://reactivemongo.org/releases/0.1x/documentation/advanced-topics/aggregation.html) – cchantep Mar 29 '20 at 23:05

1 Answers1

2

The page uses interactive shell to explain how materialised views work. In this example they define the function in the mongo shell and then call it in the same shell https://docs.mongodb.com/manual/core/materialized-views/#perform-initial-run

This is for documentation purposes only. You need to run the function to actualize the view and they do it by invoking the same function in the same shell https://docs.mongodb.com/manual/core/materialized-views/#refresh-materialized-view

You won't do it manually in prod. It must be a daemon to run the pipeline by schedule, event, or on-demand. Depending on language you are using to write the daemon the syntax may be completely different. The essential part is it must be an aggregation pipeline with the $merge stage at the end.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75