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

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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