Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Data format
  2. // createdAt is broken down to 1 day (for example 2019-10-21T00:00:00.000+00:00)
  3. // Each key in the object represents an hour of that day (so key 16 represents 2019-10-21T16:00:00.000+00:00)
  4. [{
  5.     product: 2815,
  6.     region: 'us',
  7.     createdAt: ISODate(),
  8.     location: 'Berlin',
  9.     details: {
  10.         16: { value: 2891, quantity: 2912, ... },
  11.         22: { value: 2891, quantity: 2912, ... }
  12.     }
  13. }...]
  14.  
  15.  
  16. // Aggregation
  17. // Match returns about 600 documents and takes ~95% of the total time (4-6 secs)
  18. const data = await this.db.collection('...').aggregate([
  19.       { $match: { product, createdAt: { $gte: new Date(Date.now() - sevenDaysAgo) }, region } },
  20.       { $project: { createdAt: 1, details: { $objectToArray: '$details' } } },
  21.       { $unwind: '$details' },
  22.       {
  23.         $group: {
  24.           _id: '$scannedAt',
  25.           value: { $avg: '$details.v.value' },
  26.           quantity: { $avg: '$details.v.quantity' },
  27.           ...
  28.         }
  29.       }
  30.     ]).sort({ _id: 1 }).toArray()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement