How to use MongoDB to find documents by passing a number which must be in at least one of the specific ranges of a document?

Viewed 35

Let me explain this question by starting with a basic example.

Given a collection,

[
  {
    "name": "A",
    "range": {
      "min": 10,
      "max": 100
    }
  },
  {
    "name": "B",
    "range": {
      "min": 3,
      "max": 50
    }
  }
]

And given a number N. If I want to find the documents whose range contains the number N. I can use the following query,

db.collection.find({
    "range.min": {
        $lte: N
    },
    "range.max": {
        $gte: N
    }
})

It works well.

But if the range becomes multiple, I have no idea how to do the query.

An example for the colleciton,

[
  {
    "name": "A",
    "ranges": [
      {
        "min": 10,
        "max": 20
      },
      {
        "min": 30,
        "max": 50
      },
      {
        "min": 80,
        "max": 100
      }
    ]
  },
  {
    "name": "B",
    "ranges": [
      {
        "min": 3,
        "max": 10
      },
      {
        "min": 20,
        "max": 50
      }
    ]
  }
]
2 Answers

The $elemMatch operator can be used to resolve this problem.

The following query works,

db.collection.find({
    "ranges": {
        $elemMatch: {
            "min": {
                $lte: N
            },
            "max": {
                $gte: N
            }
        }
    }
})

You can use $elemMatch to apply a combined set of filters to each of the array elements and return the record if at least one matches:

db.collection.find({
  ranges: {
    $elemMatch: {
      min: { $lte: N }, 
      max: { $gte: N }
    }
  }
})
Related