MongoDB Cache common part of aggregation

Viewed 35

I have a backend HTTP route that computes several stats about a user with aggregations. I nearly always start those with a common base so that I have enough information to work with.

They all start something like this:

Infos.aggregate([
  { $match: { owner: user._id } },
  { $lookup: { from: 'tracks', localField: 'trackId', foreignField: 'id', as: 'track' }},
  { $unwind: '$track' },

I have already indexed all the needed fields in my database (here id in tracks)

The lookup is necessary since I then filter based on the the track. The problem here is that for the moment the user has 10.000 Infos, and the lookup takes around 2300ms in total as quoted in the .explain() of the requests:

{
  '$cursor': [Object],
  nReturned: 14695,
  executionTimeMillisEstimate: 92
},
{
  '$lookup': [Object],
  nReturned: 14695,
  executionTimeMillisEstimate: 2473
},
{
  '$match': [Object],
  nReturned: 585,
  executionTimeMillisEstimate: 2505
},
{
  '$unwind': [Object],
  nReturned: 585,
  executionTimeMillisEstimate: 2505
},

I would like to know if there is a known good practice to cache the first steps of this aggregation for a specific user so that while no Infos is added, my queries will use this cache instead of re-computing every time.

Thanks

0 Answers
Related