如何更新集合中的所有文档以创建一个新字段来替换现有字段中的某些字符?

How can I update all documents in a collection to create a new field that replaces certain characters in an existing field?

我想在现有 name 的基础上向所有文档添加一个名为 searchname 的新字段,但使用 name 中的字符串并将所有 é 替换为常规 e。我如何在 shell 或驱动程序中执行此操作。我在 pymongo 中尝试这个,但我收到错误```无效的 $set :: 由 :: 表示表达式的对象必须只有一个字段``

这是我正在尝试的代码 运行

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
                            ]
                        }
        }}}}}])

查询 1

  • 管道更新需要 MongoDB >= 4.2
  • 你可以使用$replaceAll聚合运算符
  • 仅限 1 个字符

PlayMongo

update({},
[
  {
    "$set": {
      "searchName": {
        "$replaceAll": {
          "input": "$name",
          "find": "é",
          "replacement": "e"
        }
      }
    }
  }
],
{"multi": true})

查询 2

  • 用它来替换很多字符
  • 将你的 characters/replacements 放入“输入”

PlayMongo

update({},
[{"$set": 
   {"searchName": 
     {"$reduce": 
       {"input": [["é", "e"], ["l", "k"]],
        "initialValue": "$name",
        "in": 
         {"$replaceAll": 
           {"input": "$$value",
            "find": {"$arrayElemAt": ["$$this", 0]},
            "replacement": {"$arrayElemAt": ["$$this", 1]}}}}}}}],
{"multi": true})