Home > Blockchain >  check the condition if the values are less then or equal or greater than MongoDB
check the condition if the values are less then or equal or greater than MongoDB

Time:09-23

check the conditions

  1. if the value is greater equal 1000.
  2. if the value is less than equal 2000. from the parameters, the user will select either 1 or 2. User get the output in the same structure but only those documents that fulfill the condition in MongoDB
{
    "data": [
        {
            "value": 1000
        },
        {
            "value": 3000
        },
        {
            "value": 1500
        }
    ]
}

CodePudding user response:

This query answers in the question :

  • user enters 1 or 2 saved in a application variable lets say var=parameter
  • if he entered 1 => i want the documents that data.value>=1000
  • if he entered 2 => i want the documents that data.value<=1000

*also assumes that data(in your sample data) is an array not a collection.

Query

  • make {"eq" : [1 ,1]} to {"eq" : [parameter ,1]} where parameter is your variable that has the value the user selected
  • works using a condition, if the user entered 1, first comparison is made or if user entered 2 , second comparison is made
  • the comparison is done with the aggregate operators, the query operators when you compare an array(the auto take the min or max), but aggregate ones doesn't do auto, so its done here with the $max and $min operators. Istead of searching for the number we find the max/min and we compare (like query operators auto-do)

Test code here

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$cond": [
          {
            "$eq": [
              1,
              1
            ]
          },
          {
            "$gte": [
              {
                "$max": "$data.value"
              },
              1000
            ]
          },
          {
            "$lte": [
              {
                "$min": "$data.value"
              },
              2000
            ]
          }
        ]
      }
    }
  }
])
  • Related