javascript - $gte and $lte on arrays
问题描述
I have schema
{ summaries:
[
{
type: 'temp',
min: 10,
max: 40
},
{
type: 'humidity',
min: 3,
max: 40
}
],
thresholds: [
{
type: 'temp',
low: -10,
high: 40
},
{
type: 'humidity',
low: 9,
high: 30
}
]
}
This object above is one record in collection. I want to get records if summaries.type == 'temp' and thresholds.type == 'temp' and summaries.min > thresholds.low
Summaries objects compare with thresholds object must be same type. temp compare with temp, hum compare with hum. Have any summaries object temp that min < any thresholds object temp will be returned
Example:
{ summaries:
[
{
type: 'temp',
min: 10,
max: 40
},
{
type: 'humidity',
min: 3,
max: 40
}
],
thresholds: [
{
type: 'temp',
low: -10,
high: 40
},
{
type: 'humidity',
low: 9,
high: 30
}
]
}
will be returned temp min = 10, threshold low = -10.
{ summaries:
[
{
type: 'temp',
min: 10,
max: 40
},
{
type: 'humidity',
min: 3,
max: 40
}
],
thresholds: [
{
type: 'temp',
low: 20,
high: 40
},
{
type: 'humidity',
low: 9,
high: 30
}
]
}
will be not returned because temp min = 10, threshold temp low = 20 although threshold hum low = 9
解决方案
您可以使用以下查询$expr
db.collection.find({
"$expr": {
"$gt": [
{
"$arrayElemAt": [
"$summaries.min",
{ "$indexOfArray": ["$summaries.type", "temp"] }
]
},
{
"$arrayElemAt": [
"$thresholds.low",
{ "$indexOfArray": ["$thresholds.type", "temp"] }
]
}
]
}
})
推荐阅读
- google-colaboratory - 本地运行时 404 GET
- python - 将 3D 数字数组拆分为多个小数组
- swift - 将 GKObstacleNode 添加到 GKObstacleGraph 时执行中断?
- javascript - 如何访问 API 数据的特定元素?
- angular - Angular 架构:将数据从父级传递给子级
- java - SpringBoot 应用程序 GCP 部署问题
- elasticsearch - 用于elasticsearch错误的kafka连接器
- drupal - 如何使用 drupal 以编程方式创建页面?
- model-view-controller - 剑道上传不是提交时 mvc 模型的一部分
- ruby - 使用 `alias` 关键字增强方法