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

85
Vistas
How to compare two elements inside nested arrays using mongodb?

I am trying to compare the price between the first and last element inside a nested array.

The following is a part of my data:

priceRange:[
   [1600732800000,5.28424438726287],
   [1600819200000,5.08434522342211],
   [1600905600000,3.491229168216385],
   [1600992000000,4.573890580327729],
   [1601078400000,4.702973876095848]
]

So in essence I want to know if the second element inside the first array (5.28424438726287) is bigger than the second element inside the last array (4.702973876095848)


I have hard time selecting the last array inside the nested array: The folowing didn't work:

$expr: { $gt: [{ $last: "$priceRange" }, 0.000001] }

I can select the first element:

priceRange.0.1

And then there is the question how do you compare them while also having other filter constraints?

{name: "Some stock", comparing the prices}

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

0

You can add this aggregation stage:

This query create a fields called isBigger where compare the values you want:

  • The last (second) value from the first array
  • The last (second) value from the last array

And the output will be true or false if is bigger the number or not.

db.collection.aggregate([
  {
    "$project": {
      "isBigger": {
        "$cond": {
          "if": {
            "$gt": [
              {
                "$last": {
                  "$first": "$priceRange"
                }
              },
              {
                "$last": {
                  "$last": "$priceRange"
                }
              }
            ]
          },
          "then": true,
          "else": false
        }
      }
    }
  }
])

Example here

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