Advertisement
Guest User

Untitled

a guest
Sep 27th, 2017
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var StartTime = (Date.now() - (60*60*24*1000)) / 1000;
  2. var EndTime = (Date.now() / 1000);
  3. var Interval = (60*30); // half an hour (this should be dynamic as much as possible)
  4. var SensorType = "acc";
  5.  
  6. // This query takes 20 seconds (And i have 5 million records in my collection)
  7. SensorData.aggregate([
  8. {
  9.             $match: {
  10.                 date: {
  11.                     $gte: StartTime * 1000,
  12.                     $lt: EndTime * 1000
  13.                 },
  14.                 SensorType: SensorType,
  15.             }
  16.         },
  17.  
  18.         // Group by Interval
  19.         {
  20.             $group: {
  21.                 _id: Object.assign({
  22.                     timestamp: {
  23.                         $subtract: [
  24.                         {
  25.                             $divide: [ '$date', Interval * 1000]
  26.                         },
  27.                         {
  28.                             $mod: [
  29.                             {
  30.                                 $divide: ['$date', Interval * 1000]
  31.                             }, 1]
  32.                         }]
  33.                     }
  34.                 }),
  35.                 value: { $avg: "$Movement" }
  36.             }
  37.         },
  38.  
  39.         // Sort by date
  40.         {
  41.             $sort: { "_id.timestamp": 1 }
  42.         },
  43.  
  44.         // Format date & timestamp
  45.         {
  46.             $project: {
  47.                 _id: 0,
  48.                 timestamp: {
  49.                     $multiply: [Interval * 1000, "$_id.timestamp"]
  50.                 },
  51.                 value: "$value",
  52.                 date: {
  53.                     $add: [new Date(0), {
  54.                         $multiply: [Interval * 1000, "$_id.timestamp"],
  55.                     }],
  56.                 }
  57.             }
  58.         }
  59.  
  60.  
  61. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement