Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

280
Vistas
MongoDB + Javascript: Group and sort from actual hour 24 hours back

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 00h...23h or 23h...00h - but i need to start exactly at the current hour and sort the data 24h back from there.

Let's say we currently have 01:19 - it must be that way sorted (for a X-axis, from left to right): 02h-03h-04h-...23h-00h-01h, with the last hour (01h on the right) holding the last current value of that sensor in that array.

const result = db.collection('sensors').aggregate([
        {
            $match: {
                "path": path,
                "timestamp": { $gte: new Date((new Date().getTime() - (24 * 60 * 60 * 1000))) }
            }
        },
        {
            $group: {
                _id: {
                    $hour: "$_id"
                },
                avg_value: {
                    $avg: { "$toDouble": "$value"}
                },
            }
        },
        {
            $sort: {
                "_id": 1
            }
        },
    ]);

The _id is the MongoDB index object, value the sensor value and timestamp an additional new Date(Date.now()) at the sensor measurement.

UPDATE Here is the example data from MongoDB:

{
    "_id": {
        "$oid": "62606ffd5705ba9a5a79e0e1"
    },
    "path": "weather/outsideTemperature",
    "timestamp": {
        "$date": "2022-04-20T20:41:33.067Z"
    },
    "value": "1.1"
}
{
    "_id": {
        "$oid": "626076875705ba9a5a79e5fc"
    },
    "path": "weather/outsideTemperature",
    "timestamp": {
        "$date": "2022-04-20T21:09:27.328Z"
    },
    "value": "1.0"
}
{
    "_id": {
        "$oid": "626083395705ba9a5a79ef27"
    },
    "path": "weather/outsideTemperature",
    "timestamp": {
        "$date": "2022-04-20T22:03:37.652Z"
    },
    "value": "0.9"
}

Greetings, patsuhiko

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda