在 mongo shell 中使用 $regex 重命名 MongoDB 字段名称?

$rename MongoDB field names using $regex in mongo shell?

我看过其他问题,但是我看到的 none 想要修改 field 名称mongo shell 中的 $regex。我尝试将 db.collection.update$rename$regex 一起使用的尝试失败了。

我有一个 collection 文件是这样的:

{
    "_id" : "CWE-693",
    "Name" : "Protection Mechanism Failure",
    "Description" : "The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.",
    "Modes_Of_Introduction" : [
        "Architecture and Design",
        "Implementation",
        "Operation"
    ],
    "Common_Consequences" : [
        "Bypass Protection Mechanism"
    ]
}

我想重命名所有字段名称(“_id”除外)以消除下划线(“_”),因此文档看起来像这样:

{
    "_id" : "CWE-693",
    "Name" : "Protection Mechanism Failure",
    "Description" : "The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.",
    "ModesOfIntroduction" : [
        "Architecture and Design",
        "Implementation",
        "Operation"
    ],
    "CommonConsequences" : [
        "Bypass Protection Mechanism"
    ]
}

db.collection.update$rename$regex 这可能吗?是否有其他 mongo shell 编程方式来实现此目的?

$rename 只能用于纯字符串,不能用于正则表达式。

因此,您必须编写代码来读取有代表性的文档、遍历字段名称和 assemble 要执行的 $rename 操作。