How to: $merge and On-Demand-Materialized views

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.

Any help would be very much appreciated :slight_smile:

May be course instructors or others like steevej-1495 & 007_jb can help you better

I tried your steps on my Sandbox and seems to be working fine

I wanted to understand

  • where do I write this function,–at mongo prompt
  • and how I can invoke it --followed the doc
1 Like

Like @Ramachandra_37567 mentioned, the entire example is run from the Mongo shell. The function is just a wrapper around the main part… aggregate() with $merge. The materialised view is created each time $merge is executed.

All you need to do is to follow the step-by-step example and run it from the Mongo shell.

As for Play or Reactive, it’s a matter of re-translating the aggregate()part.

1 Like