Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda