title: Mongo query, intersect two ranges
body: <p>How can I optimize it? I mean even not a performance, but readability... </p>
  
  <p>It's a stage from the aggregation pipeline.
  I have to match a list of search criterias within an object.</p>
  
  <p>500 - is "from" property from the object -> static</p>
  
  <p>1000 - is "to" property from the object -> static</p>
  
  <p>I have to find all groups which intersect with the object.
  Also, a user can define "&lt;", ">" as well as "&lt;=", ">=".</p>
  
  <p>It is not always a range, the one comparison operator might be missing, so it has to search +- infinity.</p>
  
  <p>Thanks in advance!</p>
  
  <pre><code>{
    "$and": [
      {
        "$or": [
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;=" }, "attributes.value": { "$lte": 500 }
          },
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;" }, "attributes.value": { "$lt": 500 }
          },
          {
            "$and": [
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;=" }, "attributes.value": { "$gte": 500 } },
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;=" }, "attributes.value": { "$lte": 1000 } }
            ]
          },
          {
            "$and": [
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;" }, "attributes.value": { "$gt": 500 } },
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;" }, "attributes.value": { "$lt": 1000 } }
            ]
          },
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$nin": ["&gt;=", "&gt;"] }
          }
        ]
      },
      {
        "$or": [
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&lt;=" }, "attributes.value": { "$gte": 1000 }
          },
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&lt;" }, "attributes.value": { "$gt": 1000 }
          },
          {
            "$and": [
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;=" }, "attributes.value": { "$lte": 1000 } },
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;=" }, "attributes.value": { "$gte": 500 } }
            ]
          },
          {
            "$and": [
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;" }, "attributes.value": { "$lt": 1000 } },
              { "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$eq": "&gt;" }, "attributes.value": { "$gt": 500 } }
            ]
          },
          {
            "attributes.key": { "$eq": "SIZE" }, "attributes.operator": { "$nin": ["&lt;=", "&lt;"] }
          }
        ]
      }
    ]
  }
  </code></pre>