MongoDB - elemMatch with range of numbers not working as expected?

Viewed 153

I have a collection with documents which looks like this:

_id1:
Price:[1,100000]

_id2:
Price:[1,98500]

_id3:
Price:[1,3005]

..etc

Following this documentation: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

I tried reproduce the find for elements which are in a certain price range but unfortunately it doesn't work for me, I get back all of my elements even though they are not matching the criteria. What am I doing wrong?

My query:

{ Price:{ $elemMatch: { $gte: 1, $lt: 85 } } }
1 Answers

The $elemMatch has already mentioned,

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

Lets debug your document and input why its result all documents,

true = (1 >= 1 && 1 < 85)
or
false = (100000/98500/3005 >= 1 && 100000/98500/3005 < 85)

There is a value 1 which is true in every document so $elemMatch will result document if one of the element in array has true condition.


You can use alternate option to fulfil your requirement,

  • $expr to match expression conditions
  • $filter to iterate loop of Price array and match both condition,
  • $eq to check filtered Price array and actual Price array both should be same
db.collection.find({
  $expr: {
    $eq: [
      {
        $filter: {
          input: "$Price",
          cond: {
            $and: [{ $gte: ["$$this", 1] }, { $lt: ["$$this", 85] }]
          }
        }
      },
      "$Price"
    ]
  }
})

Playground

Related