You need to enable JavaScript to run this app. 如何为MongoDB集合所有文档新增替换特殊字符的字段,解决pymongo报错
优惠活动
大模型
产品
解决方案
定价
更多

如何为MongoDB集合所有文档新增替换特殊字符的字段,解决pymongo报错

报错原因

你的代码中$replaceAll表达式结构错误,你把replacement参数放到了$replaceAll的同级位置,导致in对应的对象里同时存在$replaceAll和replacement两个字段,不符合MongoDB聚合表达式要求单字段根的规则,因此触发报错。

修正后代码

MongoDB Shell 版本

test_collection.updateMany({}, [
  {
    "$set": {
      "searchName": {
        "$reduce": {
          "input": [["é","e"], ["à","a"], ["í","i"], ["ó","o"], ["ú","u"], ["ñ","n"]],
          "initialValue": { "$toLower": "$name" },
          "in": {
            "$replaceAll": {
              "input": "$$value",
              "find": { "$arrayElemAt": ["$$this", 0] },
              "replacement": { "$arrayElemAt": ["$$this", 1] }
            }
          }
        }
      }
    }
  }
])

PyMongo 版本

语法和Shell版本完全一致,直接传入即可:

test_collection.update_many({}, [
  {
    "$set": {
      "searchName": {
        "$reduce": {
          "input": [["é","e"], ["à","a"], ["í","i"], ["ó","o"], ["ú","u"], ["ñ","n"]],
          "initialValue": { "$toLower": "$name" },
          "in": {
            "$replaceAll": {
              "input": "$$value",
              "find": { "$arrayElemAt": ["$$this", 0] },
              "replacement": { "$arrayElemAt": ["$$this", 1] }
            }
          }
        }
      }
    }
  }
])

执行后会自动为所有文档新增searchName字段,完成重音字符替换和转小写处理。如果需要适配更多重音字符,直接在input的数组里补充对应的映射关系即可。

内容的提问来源于stack exchange,提问作者laneherby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:15:04