问题
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
- 500 is not less than 1000 and greater that 500
- 1000 is not less than 1000 and greater that 500
- 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