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

167
Vistas
Mongoose Aggregation to array of arrays

I have a document structure like this:

{
  readings: [
    { t: 'temperature', r: 130 },
    { t: 'humidity', r: 100 }
  ],
  created_at: '2021-01-05T10:28:49.070Z'
},
{
  readings: [
    { t: 'temperature', r: 123 },
    { t: 'humidity', r: 456 }
  ],
  created_at: '2021-01-05T10:32:50.727Z'
}

I need to aggregate the documents for a particular reading type. For example, the result of aggregation for reading type with temperature should be like following:

[
  [130, '2021-01-05T10:28:49.070Z'],
  [123, '2021-01-05T10:32:50.727Z']
]

How can I do this with an aggregation pipeline or something?

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

0

You can't output an array of arrays from an aggregate pipe. But you can output an object with a single array field. Ie:

[
  {data: [130, '2021-01-05T10:28:49.070Z']},
  {data: [123, '2021-01-05T10:32:50.727Z']}
]

Here's a pipe that does just that https://mongoplayground.net/p/7UPyUICOncq

let result = await collection.aggregate([
    {$unwind: '$readings'},
    {$match: {
      'readings.t': 'temperature'
    }},
    {"$project": {
        _id: 0,
        data: ['$readings.r', '$created_at']
    }}
])

Then to reach your desired format just map the output

let formattedResult = result.map(({data}) => data)
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