MongoDB -查找数组字段中文档的数组索引



我有包含数组字段的聚合。这个数组字段包含文档(对象)。对于这些,我有一些匹配条件,我想创建一个名为lowestCheapIndexhighestExpensiveIndex的新字段,每个字段都有匹配元素的数组索引。

匹配标准:

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,但我仍然很难在我的情况下使用它。

您可以在聚合管道中执行以下操作:

  1. 使用$map来增加records数组,使用布尔值表示低于20和超过30
  2. 使用$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
]
}
}
}
])

Mongo操场

最新更新