MongoDB:使用多个条件在数组中查找值 [英] MongoDB: find value in Array with multiple criteria
本文介绍了MongoDB:使用多个条件在数组中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据价格范围过滤文档,
I'm trying to filter documents based on their price range,
我有以下文档结构示例
{
"name": "test 1",
"priceObject" : [
{
"price" : {
"value" : 1000
}
},
{
"price" : {
"value" : 500
}
},
{
"price" : {
"value" : 333
}
}
]
}
我使用汇总来匹配价格至少为必须大于500且小于1000的文档
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
}
}
}
它返回测试1"文档,尽管它不应该,因为
it return "test 1" document, although it should not, because
- 500不小于1000并且大于500
- 1000不小于1000并且大于500
- 333不小于1000并且大于500
我该怎么做?
谢谢
推荐答案
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
}
}
}
}}
])
这篇关于MongoDB:使用多个条件在数组中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文