title: MongoDB + Javascript: Group and sort from actual hour 24 hours back
body: <p>maybe someone can help me with my problem:
  I have some sensors and if the value changes, it fires an event to write the data in the MongoDB (v4.4). What i've managed is to group all the data into 24 hours with an average value, but with the sort method i can only sort from hour <strong>00h...23h or 23h...00h</strong> - but i need to start exactly at the current hour and sort the data 24h back from there.</p>
  <p>Let's say we currently have 01:19 - it must be that way sorted (for a X-axis, from left to right): <strong>02h-03h-04h-...23h-00h-01h</strong>, with the last hour (01h on the right) holding the last current value of that sensor in that array.</p>
  <pre><code>const result = db.collection('sensors').aggregate([
          {
              $match: {
                  &quot;path&quot;: path,
                  &quot;timestamp&quot;: { $gte: new Date((new Date().getTime() - (24 * 60 * 60 * 1000))) }
              }
          },
          {
              $group: {
                  _id: {
                      $hour: &quot;$_id&quot;
                  },
                  avg_value: {
                      $avg: { &quot;$toDouble&quot;: &quot;$value&quot;}
                  },
              }
          },
          {
              $sort: {
                  &quot;_id&quot;: 1
              }
          },
      ]);
  </code></pre>
  <p>The <strong>_id</strong> is the MongoDB index object, <strong>value</strong> the sensor value and <strong>timestamp</strong> an additional <code>new Date(Date.now())</code> at the sensor measurement.</p>
  <p><strong>UPDATE</strong>
  Here is the example data from MongoDB:</p>
  <pre><code>{
      &quot;_id&quot;: {
          &quot;$oid&quot;: &quot;62606ffd5705ba9a5a79e0e1&quot;
      },
      &quot;path&quot;: &quot;weather/outsideTemperature&quot;,
      &quot;timestamp&quot;: {
          &quot;$date&quot;: &quot;2022-04-20T20:41:33.067Z&quot;
      },
      &quot;value&quot;: &quot;1.1&quot;
  }
  {
      &quot;_id&quot;: {
          &quot;$oid&quot;: &quot;626076875705ba9a5a79e5fc&quot;
      },
      &quot;path&quot;: &quot;weather/outsideTemperature&quot;,
      &quot;timestamp&quot;: {
          &quot;$date&quot;: &quot;2022-04-20T21:09:27.328Z&quot;
      },
      &quot;value&quot;: &quot;1.0&quot;
  }
  {
      &quot;_id&quot;: {
          &quot;$oid&quot;: &quot;626083395705ba9a5a79ef27&quot;
      },
      &quot;path&quot;: &quot;weather/outsideTemperature&quot;,
      &quot;timestamp&quot;: {
          &quot;$date&quot;: &quot;2022-04-20T22:03:37.652Z&quot;
      },
      &quot;value&quot;: &quot;0.9&quot;
  }
  </code></pre>
  <p>Greetings, patsuhiko</p>