Search code examples
mongodbpymongo

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}


Solution

  • 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