mongodb - MongoDB - 在数组字段中查找文档的数组索引
问题描述
我有包含数组字段的聚合。该数组字段包含文档(对象)。对于这些,我有一些匹配条件,我想创建一个名为lowestCheapIndex
and的新字段highestExpensiveIndex
,每个字段都有匹配元素的数组索引。
匹配标准:
lowestCheapIndex
- 应包含价格低于 20 的任何记录项的最低数组索引号。
highestExpensiveIndex
- 应包含价格超过 30 的任何记录项的最高数组索引号。
我当前的聚合输出:
{
'_id': 'Egg shop',
'records': [
{'_id': 1, 'price': 22},
{'_id': 2, 'price': 18},
{'_id': 3, 'price': 34},
{'_id': 4, 'price': 31},
{'_id': 5, 'price': 13},
]
}
期望的输出:
{
'_id': 'Egg shop',
'records': [
{'_id': 1, 'price': 22},
{'_id': 2, 'price': 18},
{'_id': 3, 'price': 34},
{'_id': 4, 'price': 31},
{'_id': 5, 'price': 13},
],
'lowestCheapIndex': 1,
'highestExpensiveIndex': 3,
}
问题:
如何根据我的条件检索数组索引?我$indexOfArray
在文档中找到了,但我仍然很难在我的情况下如何使用它。
解决方案
您可以在聚合管道中执行以下操作:
- 用于使用指示低于 20 和超过 30 的布尔值
$map
来扩充您的数组records
- 用于
$indexOfArray
搜索布尔值;对于highestExpensiveIndex
,首先反转数组以获得索引,然后从数组的大小中减去它 - 1 以获得预期的索引。
db.collection.aggregate([
{
"$addFields": {
"records": {
"$map": {
"input": "$records",
"as": "r",
"in": {
"_id": "$$r._id",
"price": "$$r.price",
"below20": {
$lt: [
"$$r.price",
20
]
},
"over30": {
$gt: [
"$$r.price",
30
]
}
}
}
}
}
},
{
"$addFields": {
"lowestCheapIndex": {
"$indexOfArray": [
"$records.below20",
true
]
},
"highestExpensiveIndex": {
"$subtract": [
{
"$subtract": [
{
$size: "$records"
},
{
"$indexOfArray": [
{
"$reverseArray": "$records.over30"
},
true
]
}
]
},
1
]
}
}
}
])
推荐阅读
- scala - Scala:如何在未来管理致命错误(如 OOM)
- algorithm - 如何在没有箭头的图上进行深度优先搜索?
- vue.js - Nuxt.js 自定义存储文件夹
- c# - 通过 WMI (C#) 检索当前登录用户的用户名
- java - 如何在java日志中将数据记录到excel中
- android - Anyplace 开源
- docker-swarm - docker-swarm 成对运行容器
- go - 使用 go-flags 添加多个命令
- c++ - 将 lua 与 c++ dll 一起使用
- apache-kafka - Kafka 消费者总是给出 java.nio.channels.ClosedChannelException