【问题标题】:$rename MongoDB field names using $regex in mongo shell?$rename MongoDB 字段名称在 mongo shell 中使用 $regex?
【发布时间】:2018-12-10 15:07:48
【问题描述】:

我查看了其他问题,但没有人希望在 mongo shell 中使用 $regex 修改 字段 名称。我尝试将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 编程方式来实现这一点吗?

【问题讨论】:

  • @JohnnyHK 好吧,我想这就是答案。把它写在这里作为答案,我会接受的。

标签: regex mongodb mongodb-query rename updating


【解决方案1】:

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

因此,您必须编写代码来读取代表性文档,遍历字段名称并组装 $rename 操作来执行。

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多