从 mongodb 的嵌套数组中提取找到的值及其索引

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

具有嵌套数组的示例数据:

[
  {
    "rows": [["123", "234", "345"], ["345", "456", "567"]]
  },
  {
    "rows": [["111", "222", "333"], ["444", "555", "345"]]
  },
]

给定一个特定值(例如

345
),我想将找到的值及其第一个数组索引(例如
row_i
)和第二个数组索引(例如
col_i
)聚合到结果中:

[
  {"value": "345", "row_i": 0, "col_i": 2},
  {"value": "345", "row_i": 1, "col_i": 0},
  {"value": "345", "row_i": 1, "col_i": 2},
]

我知道如何使用

$elemMatch
聚合整个文档(示例 1),但这不包括行/列索引。

我尝试使用

$unwind
,但只能使其适用于嵌套对象,而不适用于数组(示例 2)。我有一个限制,我根本无法更改数据结构。

arrays mongodb aggregation-framework
1个回答
0
投票

对于 row_i,您可以使用

$unwind
includeArrayIndex
来生成行索引。对于 col_i,您可以使用
$indexOfArray
来获取行内的索引。

db.collection.aggregate([
  {
    "$unwind": {
      path: "$rows",
      includeArrayIndex: "row_i"
    }
  },
  {
    "$set": {
      "col_i": {
        "$indexOfArray": [
          "$rows",
          "345"
        ]
      }
    }
  },
  {
    $match: {
      "col_i": {
        $ne: -1
      }
    }
  },
  {
    "$project": {
      "value": "345",
      "row_i": 1,
      "col_i": 1
    }
  }
])

蒙戈游乐场

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