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

420
Vistas
MongoDB (Mongoose) - grouping data under a unique field

In the collection, I have entries as such:

[
    {
        _id: new ObjectId('61cae11f8fc0b2e3b045be04'),
        location: 'Station One',
        datetime: ISODate('2019-02-02T12:54:57.937Z'),
        sensorType: 'temperature',
        value: -1.8,
        __v: 0,
    },
    {
        _id: new ObjectId('61cae11f8fc0b2e3b045be05'),
        location: 'Station two',
        datetime: ISODate('2019-02-02T09:49:39.200Z'),
        sensorType: 'temperature',
        value: -2,
        __v: 0,
    },
];

I have a aggregate query to get min/max values of each sensortype like so

const queryMinMax = FarmDataModel.aggregate([
    {
        $match: match,
    },
    {
        $sort: {
            value: 1,
        },
    },
    {
        $group: {
            _id: {
                sensorType: '$sensorType', location: '$location',
            },
            min: {
                $first: '$$ROOT',
            },
            max: {
                $last: '$$ROOT',
            },
        },
    },
    {
        $sort: {
            '_id.location': 1,
            '_id.sensorType': 1,
        },
    },
    {
        $project: {
            _id: 1,
            max: {
                value: '$max.value',
                month: { $month: '$max.datetime' },
                year: { $year: '$max.datetime' },
                day: { $dayOfMonth: '$max.datetime' },
            },
            min: {
                value: '$min.value',
                month: { $month: '$min.datetime' },
                year: { $year: '$min.datetime' },
                day: { $dayOfMonth: '$min.datetime' },
            },
        },
    },
]);

This gets me a row for each sensortype and corresponding min max values. What Id like to do is group each sensortype under a location, so that query would return something like so:

{
    'Station One': {
        temperature: {
            min: { value: number; date: date }
            max: { value: number; date: date },
        },
        pH: {
            min: { value: number; date: date }
            max: { value: number; date: date },
        },
    },

    'Station Two': {
        temperature: {
            min: { value: number; date: date }
            max: { value: number; date: date },
        },
        pH: {
            min: { value: number; date: date }
            max: { value: number; date: date },
        },
    },
};

So if before I would get 4 rows, one for each sensorType in each location, now I would get two rows, one for each location and under those there are key:value pairs for each sensorType

Hoe can I modify my query to achieve that?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can just build on your existing pipeline, all it takes is another $group stage to group the data by station, then some restructuring of it to match the output you want, like so:

db.collection.aggregate([
  ... existing pipeline,
  {
    $group: {
      _id: "$_id.location",
      sensorData: {
        $push: {
          k: "$_id.sensorType",
          v: {
            max: "$max",
            min: "$min"
          }
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": [
          [
            {
              k: "$_id",
              v: {
                "$arrayToObject": "$sensorData"
              }
            }
          ]
        ]
      }
    }
  }
])

Mongo Playground

over 4 years ago · Santiago Trujillo Denunciar
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