MongoDB:如何获取多个 $indexOfArray 值?

问题描述 投票:0回答:1

我有一个文档,其中数组的索引有意义。在 MongoDB 聚合中,如何返回数组中与特定值匹配的所有索引? $indexOfArray 仅返回第一项。

例如,与:

{ 
    data: [-1, 100, 150, 200, -1, -1] 
}

如果我正在寻找 -1,我希望收到:[0, 4, 5]。

mongodb aggregation-framework
1个回答
0
投票

有很多方法可以做到这一点

可以使用

$filter
来过滤索引数组。索引数组的每次迭代(i)都会根据条件检查是否过滤掉
data[i] == -1
和相等的。

db.collection.aggregate([
  {
    $project: {
      indices: {
        $filter: {
          input: { $range: [ 0, { $size: "$data" } ] },
          cond: { $eq: [ { $arrayElemAt: [ "$data", "$$this" ] }, -1 ] }
        }
      }
    }
  }
])

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.