2

I'm trying to filter documents based on their price range,

i have the following document structure example

{
    "name": "test 1",
    "priceObject" : [
        {
            "price" : {
                "value" : 1000
            }
        },
        {
            "price" : {
                "value" : 500
            }
        },
        {
            "price" : {
                "value" : 333
            }
        }
    ]
}

i use aggregate to match documents that have at least one price that must be greater than 500 and less than 1000

{
    "$match": {
        "priceObject.price.value": {
            "$gt": 500,
            "$lt": 1000
        }
    }
}

it return "test 1" document, although it should not, because

  1. 500 is not less than 1000 and greater that 500
  2. 1000 is not less than 1000 and greater that 500
  3. 333 is not less than 1000 and greater that 500

how can i do that?

Thanks

1 Answer 1

1

If you specify more than one condition to query an array then you have to use $elemMatch query operator

db.collection.aggregate([
  { "$match": {
    "priceObject": {
      "$elemMatch": {
        "price.value": {
          "$gt": 500,
          "$lt": 1000
        }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.