Home > database >  MongoDB sort by value in nested array
MongoDB sort by value in nested array

Time:10-06

I have a collection called datos_sensores which documents store data from 2 sensors, one for temperature and humity and other one for CO2 and consume. There are 2 location for those sensors, location_id:1 and location_id:2. The documents has the following structure, in example:

{
    _id: ObjectId("632eccf6c4c33123d451e23f"),
    timestamp: '2020-07-02T17:45:00Z',
    sensor_id: 1,
    location_id: 2,
    medidas: [
      { tipo_medida: 'Temperatura', valor: 36.76, unidad: 'ºC' },
      { tipo_medida: 'Humedad_relativa', valor: 3.77, unidad: '%' }
    ]
  }

I want to get the minimum value of location_id:2 of the element "valor" inside of the array "medidas". However, if you pay attetion, there are 2 valor fields. I want to get the minimum Temperature value, and not the minimum Humity value (Humedad_relativa). I tried the following:

sensores_IoT> db.datos_sensores.find({"medidas.tipo_medida":"Temperatura",location_id:2}).sort({"medidas.valor":1}).limit(1)

And got this answer:

[
  {
    _id: ObjectId("632ecd14c4c33123d451e67d"),
    timestamp: '2020-07-05T14:00:00Z',
    sensor_id: 1,
    location_id: 2,
    medidas: [
      { tipo_medida: 'Temperatura', valor: 39.51, unidad: 'ºC' },
      { tipo_medida: 'Humedad_relativa', valor: 0.3, unidad: '%' }
    ]
  }
]

As you can see, I am getting the list sorted by humity and not for temperature. How can I tell to mongo to sort by the value tipo_medida.valor of the Temperature?

After that, I need to use $mul to multiply the value by 1.2, but I think it's quite easy to do once I have the objected filtered.

Thank you very much in advance.

CodePudding user response:

This should work, here we are first sorting by medidas.tipo_medida, and then by medidas.valor:

db.datos_sensores.find({"medidas.tipo_medida":"Temperatura",location_id:2})
                 .sort({"medidas.tipo_medida": -1,"medidas.valor":1}).limit(1)
  • Related