Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!