如何修复 MongoDB 数组连接错误?

How to fix MongoDB array concatination error?

我在 mongodb 中有一个集合,其中包含几百万个文档。有一个属性(类别)是一个包含文档所属的所有类别的数组。我正在使用以下查询将数组转换为逗号分隔的字符串,以通过勺子转换将其添加到 SQL 服务器。 例如 文档有 ["a","b","c",...] 我需要 a,b,c,... 所以我可以把它放在一个列中

categories: {
        $cond: [
          { $eq: [{ $type: "$categories" }, "array"] },
          {
            $trim: {
              input: {
                $reduce: {
                  input: "$categories",
                  initialValue: "",
                  in: { $concat: ["$$value", ",", "$$this"] }
                }
              }
            }
          },
          "$categories"
        ]
      }

当我 运行 查询时出现以下错误,我无法弄清楚问题所在。

com.mongodb.MongoQueryException: Query failed with error code 16702 and error message '$concat only supports strings, not array' on server

一些文档将此属性作为字符串而不是数组,因此我添加了类型检查。但问题仍然存在。非常感谢任何有关如何缩小问题范围的帮助。

同一个集合中的一些其他属性相同,此查询对其余属性运行良好。

我没有发现您的汇总有任何问题。它不应该给出这个错误。您可以尝试更新您的 mongodb 版本吗?

但是,您的聚合没有正常工作reduce没有工作。我将其转换为:

db.collection.aggregate([
    {
        "$project": {
            categories: {
                $cond: [
                    {
                        $eq: [{ $type: "$categories" }, "array"]
                    },
                    {
                        '$reduce': {
                            'input': '$categories',
                            'initialValue': '',
                            'in': {
                                '$concat': [
                                    '$$value',
                                    { '$cond': [{ '$eq': ['$$value', ''] }, '', ', '] },
                                    '$$this'
                                ]
                            }
                        }
                    },
                    "$categories"
                ]
            }
        }
    }
])

编辑:

因此,如果您在 categories 字段中有嵌套数组。我们可以用 unwind 阶段展平我们的阵列。因此,如果您可以在 $project 阶段之上添加这 3 个阶段。我们的聚合将起作用。

  {
    "$unwind": "$categories"
  },
  {
    "$unwind": "$categories"
  },
  {
    "$group": {
      _id: null,
      categories: {
        $push: "$categories"
      }
    }
  },

Playground