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

时间:2018-12-10 15:07:49

标签: regex mongodb mongodb-query rename updating

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

我有一个包含以下文档的收藏集:

{
    "_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编程方式可以实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

$rename仅可与纯字符串一起使用,而不能与正则表达式一起使用。

因此,您必须编写代码以阅读具有代表性的文档,遍历字段名并组合一个$rename操作才能执行。