MongoDB 带有嵌套数组的映射过滤器未按预期工作

MongoDB map-filter with nested arrays not working as expected

我有具有以下架构的文档:

[
  {
    "documentKey": "documentData",
    "functions": [
      {
        "name": "firstFunction",
        "outerArray": ["elements", "in", "the", "array"],
        "objectsToBeFiltered": [
          {
            "objectName": "firstObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["a", "b"]
          },
          {
            "objectName": "secondObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["z"]
          }
        ]
      },
      {
        "name": "secondFunction",
        "outerArray": ["elements", "in", "the", "array"],
        "objectsToBeFiltered": [
          {
            "objectName": "firstObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["m"]
          },
          {
            "objectName": "secondObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["a"]
          }
        ]
      }
    ]
  }
]

我想在 columns

中丢弃没有 "a"objectsToBeFiltered 数组元素

我经历过这个 for a similar problem but replicating it has not worked out for me: Mongo Playground。对于 functions 数组中的所有对象,我以空 objectsToBeFiltered 数组结束。

我的预期输出是:

[
  {
    "documentKey": "documentData",
    "functions": [
      {
        "name": "firstFunction",
        "outerArray": ["elements", "in", "the", "array"],
        "objectsToBeFiltered": [
          {
            "objectName": "firstObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["a", "b"]
          }
        ]
      },
      {
        "name": "secondFunction",
        "outerArray": ["elements", "in", "the", "array"],
        "objectsToBeFiltered": [
          {
            "objectName": "secondObject",
            "innerArray": ["elements", "in", "the", "array"],
            "columns": ["a"]
          }
        ]
      }
    ]
  }
]

你只需要使用 $in 而不是 $eq

as $eq 比较类型和值,所以你试图在数组中搜索具有 columns = 'a' 的元素,所以列应该是一个字符串并且有一个 value = 'a'

$in 使您能够检查某个值是否存在于数组中

db.collection.aggregate([
  {
    "$addFields": {
      functions: {
        $map: {
          input: "$functions",
          as: "fld2",
          "in": {
            name: "$$fld2.name",
            outerArray: "$$fld2.outerArray",
            objectsToBeFiltered: {
              $filter: {
                input: "$$fld2.objectsToBeFiltered",
                as: "fld4",
                cond: {
                  "$in": [
                    "a", // the value you're looking for
                    "$$fld4.columns" // the array to search in
                  ]
                }
              }
            }
          }
        }
      }
    }
  }
])

这是一个工作示例Mongo Playground