MongoDB: find value in Array with multiple criteria

蹲街弑〆低调 提交于 2020-01-15 04:16:26

问题


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:


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
        }
      }
    }
  }}
])


来源:https://stackoverflow.com/questions/57198654/mongodb-find-value-in-array-with-multiple-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!